Reputation: 359
I need some help or just a simple example for the following situation: (Obviously I have searched and googled for hours without any satisfying outcome)
I have a lot of text comments stored in CoreData, which I want to assemble into one big html string to display them in a webview. So I have a really simple loop which iterates through all core data entries and appends the new bit onto an existing string. What I see in Instruments is that every time I do an append to string operation, a new CFstring
is allocated with slightly larger size than the previous one, ending in a crash with GB's of strings allocated. (at the moment I'm using [myMutableString appendFormat:@"%@", myCoreDataReference]
So as I see from which corner the problem is coming from, I have tried everything I can think of as an amateur developer, obviously using NSMutable strings. Apparently I'm still doing something wrong here, since the problem still remains in some form at least.
If anyone can provide me with a simple example for a loop appending to a string each time with correct memory management, I would be grateful. (I'm using ARC)
Cheers, Bob
Upvotes: 0
Views: 80
Reputation: 1500
It's always recommended that you create an autorelease pool for the code block when you are performing operations in a tight loop.
for(int i = 0; i<yourCommentStringArrayCount; i++)
{
@autoreleasepool
{
//Do the append operation
}
}
This makes sure that any allocated memory is released as soon as the the code block is executed for that iteration.
Upvotes: 1
Reputation: 2503
Let's try:
// just my example
for (int i = 0; i < 10000; i++)
{
// do autoreleasepool here to be sure that myCoreDataReference will be deallocated
@autoreleasepool {
NSString *myCoreDataReference = [NSString stringWithFormat@"%d",i];
[myMutableString appendFormat:@"%@", myCoreDataReference]
}
}
Upvotes: 1