开发者

Cannot reset NSArray and NSMutableArray in Objective-C

I create an NSMutableArray as follows (note that winner is an instance variable):

winner = [NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil];

When I set winner to nil or remove its objects like

[self.winne开发者_如何学编程r removeAllObjects];

my program will automatically shut down. How should I solve this?

Updated !!! In case I code like this

self.winner = [NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil];

it will call setter method which is

- (void)setWinner:(NSMutableArray *)newWinner
{
    [winner release];
    winner = [newWinner retain];
}

Do I still need to retain the array like

self.winner = [[NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil] retain];


Are you calling -removeAllObjects in a different method? If so, then the problem is likely that you've failed to retain the array, and it has been destroyed between the assignment and your later reference. +arrayWithObjects returns an instance that has had autorelease called on it.

Either use a synthesized property to set the instance variable, use a method that returns ownership of the object (like +alloc), or add a retain call:

winner = [[NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil] retain];


You didnt allocated the array

SO do like,

winner = [[NSMutableArray alloc] initWithArray:@"11", @"12", @"13", nil];


You assigned an autoreleased reference to an instance variable, so it gets dealloced after the event loop. Just retain it after creating it:

winner = [[NSMutableArray arrayWithObjects:@"11", @"12", @"13", nil] retain];


Your program is not shutting down for what you're showing there, there's nothing wrong with it. Show us what error code you get and whether an exception is being thrown and post a bit more code around where the crash is happening.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜