Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to release a copied NSObjects - Objective-c

I was wondering if I need to release a copied NSObject? For example, I create only one dictionary that I copy into an array:

Code:

for (int num = 0; num < [object count]; num++) {
    [dictionary setObject:[object objectAtIndex:num] forKey:@"x"];
    [array addObject:[dictionary copy]];
}

Do I have to release the dictionary? If yes, when?

Thanks

like image 640
ncohen Avatar asked Mar 12 '10 01:03

ncohen


People also ask

What is copy Objective C?

copy -- It creates a new object and when new object is created retain count will be 1.

How do I create an NSObject in Objective C?

Creating a Custom Class Go ahead an choose “Objective-C class” and hit Next. For the class name, enter “Person.” Make it a subclass of NSObject. NSObject is the base class for all objects in Apple's developer environment. It provides basic properties and functions for memory management and allocation.

What is NSCopying in swift?

NSCopying declares one method, copy(with:) , but copying is commonly invoked with the convenience method copy() . The copy() method is defined for all objects inheriting from NSObject and simply invokes copy(with:) with the default zone.


3 Answers

Yes, you do. In this case, you should probably release the copy immediately after adding it to the array, because the array retains anything added to it:

 NSDictionary *copied = [dictionary copy];
 [array addObject:copied];
 [copied release];
like image 116
Noah Witherspoon Avatar answered Oct 18 '22 20:10

Noah Witherspoon


This fragment from documentation:

- (id)copy

Return Value The object returned by the NSCopying protocol method copyWithZone:, where the zone is nil.

Discussion This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copyWithZone:.

NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

Special Considerations If you are using managed memory (not garbage collection), this method retains the new object before returning it. The invoker of the method, however, is responsible for releasing the returned object.

like image 5
Victor Avatar answered Oct 18 '22 18:10

Victor


With copy, you take ownership of the returned object. Containers also take ownership of the objects added to them.
As a result, you have to relinquish ownership of the copy as Noah pointed out. The Cocoa memory management guidelines contain a section noting how to work with containers.

like image 2
Georg Fritzsche Avatar answered Oct 18 '22 19:10

Georg Fritzsche