开发者

how to properly retain data read from plist?

开发者 https://www.devze.com 2023-04-01 12:52 出处:网络
I am stuck debugging a NSInvalidArgumentException. My latest suspicion is that I didn\'t retain the data read from plist properly so that it\'s occupied by some other object while I access it.

I am stuck debugging a NSInvalidArgumentException. My latest suspicion is that I didn't retain the data read from plist properly so that it's occupied by some other object while I access it.

My plist structure is very complicated, it has 8 levels of arrays/dictionaries. I think I lost the memory when I try to access the lowest object.

I wonder if I have to retain every data element when I read the plist file or is it sufficient to just retain the top level object?

This is how I read:

NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSError *error = [[[NSError alloc] init] autorelease];
NSArray *temp = (NSArray *)[[NSPropertyListSerialization
                            propertyListWithData:plistXML 
                            options:NSPropertyListMutableContainersAndLeaves
                            format:nil 
                            error:&error] retain];
self.dataPackage = [temp objectAtIndex:0];

dataPackage is declared as:

@interface rootViewController:UIViewController{
  NSDictionary 开发者_开发知识库*dataPackage;
}
@property (retain) NSDictionary *dataPackage;

and synthesized:

@synthesize dataPackage;

Am I doing it right?

Thanks

Leo


I noticed 3 things:

  • You don't need to create an NSError object! NSPropertyListSerialization will return an error object if something fails. Just init with: NSError *error = nil;

  • You don't have to retain the (autoreleasing) temp-array, you obviously don't need the whole array after fetching the object at index 0.

  • [temp objectAtIndex:0] will crash when the array is empty!

Be sure to release the property var in dealloc with self.dataPackage = nil. Then everything is safe from memory management perspective.


Please go through the structure of Plist in TextEdit.... For more go through my previous post If you are using Xcode 4 then this might be the reason. The structure might got changed in xcode 4.

0

精彩评论

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

关注公众号