NSString在发布时崩溃

时间:2011-07-12 04:22:29

标签: objective-c ios memory-management nsstring

这是我的ItemInfo类接口

@interface ItemInfo : NSObject {
    NSString *item;
}
@property (nonatomic, copy) NSString *ipaddress;

......和实施

@synthesize item;
- (id) initWithItem:(NSString *)someItem {
    self = [super init];
    if(self) {
        item = someItem;   // Ideally these things should happen here. 
                           // Since item is a NSString and not NSMutableString,
                           // it should be sent a retain, thus
                           // making its refcount = 1
                           // Is my understanding correct?
    }
    return self;
}

- (void) dealloc {
    [item release];   // I own 'item', so I should release it when done
    [super dealloc];
}

我正在从其他地方使用这个类:

char *str = inet_ntoa(addy->sin_addr);
ItemInfo *h = [[ItemInfo alloc] initWithItem:[NSString stringWithFormat:@"%s", str]];
ContentBrowserViewController *d 
        = [[ContentBrowserViewController alloc] initWithItemInfo:h]; 
[self.navigationController pushViewController:d animated:YES];
[h release];
[d release];

我遇到的崩溃是 *** -[CFString release]: message sent to deallocated instance 0x62255700x6225570h.item

的地址

我哪里错了?

2 个答案:

答案 0 :(得分:4)

您需要使用self.item = someItem致电您的二传手。您目前忽略了setter,因此不会复制/拥有String。

答案 1 :(得分:3)

initWithItem:中,您需要执行item = [someItem copy]; 也可以item = [someItem retain];,但如果您的字符串是NSMutableString,则会导致问题。< / p>

崩溃的原因是你传递了一个自动释放的字符串,而你的initWithItem:没有说“我需要这个字符串留在”(保留)或 “我需要这个字符串的个人版本”(复制)。因此,当您在dealloc中释放字符串时,字符串会过于频繁地释放。

根据你的消息来源,我愿意打赌,你发布的代码中没有发生崩溃,但实际上当NSAutoreleasePool最终释放字符串时。

相关问题