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
copy -- It creates a new object and when new object is created retain count will be 1.
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.
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.
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];
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With