Search code examples
objective-cmemory-managementios6xml-parsing

Factory methods in objective c


I am parsing an xml feed (with a NSXML parser) where I need to create a bunch of the same object, foo, and then add these objects to a NSMutableArray. My question concerns memory management while I attempt this.

As I see it, my two options are: 1) Create a factory method that creates the objects as I need them. This is my factory method, which I've added as a method in the xml parser.

+ (id)create_foo
{
return [[foo alloc] init];
}

2) I have automatic reference counting on. So I was thinking that I could create a single foo object as an instance variable in the xml parser and let the auto memory management take care of releasing the object when I need to create a new foo object. So in the didStartelement method of the NSXML parser

if ([elementName isEqualToString:@"new_foo"])
{
    current_foo = [foo alloc];
}

Which is more efficient? The second option seems like less work, but I'm worried about the auto reference counting. Is there a third option?


Solution

  • Do you have a measurable performance bottleneck that you have identified?

    If not, don't worry about it.

    And if you use ARC, the compiler/runtime will optimize away the use of autorelease wherever possible (which includes factory methods).