代码之家  ›  专栏  ›  技术社区  ›  Steve Harrison

从UITableView委托方法访问实例变量

  •  1
  • Steve Harrison  · 技术社区  · 17 年前

    问题:

    我正在尝试从UITableView访问变量 tableView:didSelectRowAtIndexPath:

    applicationDidFinishLaunching

    奇怪的是,如果我这样声明变量,问题就不会出现:

    helloWorld = @"Hello World!";
    

    helloWorld = [NSString stringWithFormat: @"Hello World!"];
    

    对这里可能发生的事情有什么想法吗?我错过了什么?

    UntitledAppDelegate.h:

    #import <UIKit/UIKit.h>
    
    @interface UntitledAppDelegate : NSObject <UIApplicationDelegate, UITableViewDelegate, UITableViewDataSource>  {
        UIWindow *window;
        NSString *helloWorld;
    }
    
    @property (nonatomic, retain) IBOutlet UIWindow *window;
    
    @end
    

    #import "UntitledAppDelegate.h"
    
    @implementation UntitledAppDelegate
    
    @synthesize window;
    
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
    
        helloWorld = [NSString stringWithFormat: @"Hello World!"];
    
        NSLog(@"helloWorld: %@", helloWorld); // As expected, logs "Hello World!" to console.
    
        [window makeKeyAndVisible];
    }
    
    - (void)dealloc {
        [window release];
        [super dealloc];
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
         return 1;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *MyIdentifier = @"MyIdentifier";    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
        }   
        cell.textLabel.text = @"Row";
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        NSLog(@"helloWorld: %@", helloWorld); // App crashes
    }
    
    @end
    
    1 回复  |  直到 17 年前
        1
  •  3
  •   Ben Gottlieb    13 年前

    你需要保留你的 helloWorld

    helloWorld = [[NSString stringWithFormat: @"Hello World!"] retain];
    

    它在第一个实例中起作用,因为静态字符串被“无限保留”,因此永远不会被释放。在第二种情况下,一旦事件循环运行,就会释放实例变量。保留它将防止这种情况。