开发者

NSString crash on release

开发者 https://www.devze.com 2023-03-19 08:15 出处:网络
Here is my ItemInfo class interface @interface ItemInfo : NSObject { NSString *item; } @property (nonatomic, copy) NSString *ipaddress;

Here is my ItemInfo class interface

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

... and the implementation

@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];
}

I am using this class from elsewhere like thus:

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];

The crash I am encountering is *** -[CFString release]: message sent to deallocated instance 0x6225570. 0x6225570 is the address of h.item

Where am I going wrong?


You need to call your setter using self.item = someItem. You currently disregard the setter and therefore do not copy/own the String.


In your initWithItem:, you need to do item = [someItem copy]; You could also do item = [someItem retain];, but that would cause problems if your string was a NSMutableString.

The reason for the crash is that you pass an autoreleased string, and your initWithItem: doesn't say "I need this string to stay around" (retain) or "I need my personal version of this string" (copy). The string thus gets released too often as you do release it in your dealloc.

According to your source, I'm willing to bet that the crash does not happen in the code you've posted but actually when the NSAutoreleasePool is finally releasing the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消