开发者

NSMutableArray: how to fill it with data, release it, fill it with data again

I have a NSMutableArray in my app which I initiate like this:

H-FILE

NSMutableArray *noteBookContent;
@property (nonatomic, retain) NSMutableArray *noteBookContent;

M-FILE

@synthesize noteBookContent;

I then have a method in which I open a txt file and read its contents into a temp NSString and slices this NSString into different bits which are then put into the NSMutableArray. Like so:

    NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
                                                          encoding:NSUTF8StringEncoding
                                                             error:&error];

self.noteBookContent = [[[tempTextOut componentsSeparatedByString: @"\n[DIVIDER]\n"] mutableCopy] autorelease];

My big question is what happens if I repeat the same process a couple of times. Is there a need to release the noteBookContent before I read new data into it? Is there a chance of data being messed up, e.g. if one noteBookContent has 10 items (all called FRUIT) and the next noteBookContent has 5 items (all called SALAD), may I end up 开发者_Go百科with SALAD, SALAD, SALAD, SALAD, SALAD, FRUIT, FRUIT, FRUIT, FRUIT etc.?

Sorry if this is obvious, but I don't really understand what happens in the moment that I read new data into an NSMutableArray which already contains old data.

Thanks for any explanations!


In this case you’re not actually changing the contents of the array—you’re replacing the object entirely. The old value of noteBookContent—the NSMutableArray instance—gets released by the property assignment (the .noteBookContent = ...), and replaced with a new, separate NSMutableArray that’s created by the -mutableCopy call. A more efficient way to do it would be this:

[self.noteBookContent removeAllObjects];
[self.noteBookContent addObjectsFromArray:[tempTextOut componentsSeparatedByString: @"\n[DIVIDER]\n"]];


You don't need to do anything, because you are using a property. This property automatically handles the memory management of your mutable array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜