Can objects manage their own destruction (using ARC)? - objective-c

I have a controlling parent class that needs to perform several actions, these actions typically have a very short lifespan. I'm using a Factory class to create these objects and have some questions about how to best manage their demise and if more than one can safely co-exist. Here some example pseudo code:
#interface parent
#property (strong, nonatomic) abstractChild* action;
- (abstractChild*) makeConcreteChildOfType:(Type)type;
- (void) performActionA;
- (void) performActionB;
- (void) performActionC;
...
- (void) performActionA;
{
self.action = [self makeConcreteChildOfType:A];
[self.action doYourThing];
}
- (void) performActionB;
{
self.action = [self makeConcreteChildOfType:B];
[self.action doYourThing];
}
I have quite a lot of different types of actions and each child action class knows what it has to do and when its finished doing it.
I could create separate properties for each different type of concrete action instead of having one abstract property, and have each child object inform the parent when its finished via a delegate, however that's starting to get a little messy especially when the fact that multiple actions of the same type could potentially be active at once (which would require arrays of pointers to objects of each type). Therefore I'm wondering if/how the child objects can manage themselves, specifically their own destruction.
If each object looked something like this:
#implementation ChildObjectA
-(void) doYourThing
{
[self retain];
do something
}
- (void) OnCompletion
{
[self release];
}
Then is this safe to do? - could the parent class create multiple objects of the same type and they all live for as long as each is needed and effectively are deleting themselves when done and they can exist in parallel and delete themselves when done without issue?
There is presumably no need for the action property of the parent class, but if it was kept then I'd like to confirm there's no problems with memory management that arise? I presume not as each time self.action is assigned to ARC will release the associated child object but it won't be deleted until the child object releases itself?

It's certainly possible for an object to own itself, but the cases where it's truly necessary are few and far between. I don't think this is one of them.
I think the solution that you've called "too messy" is in fact the best one. It's also, to my mind, quite simple and clean. The factory keeps a collection of action objects.* When an action object is done, it informs the factory, which cleans it up. This is similar to the activity of an NSOperationQueue -- the queue takes ownership of the operations.
#implementation Factory
{
NSMutableArray * listOfAllActions;
}
- (void) performActionA;
{
Action * newAction = [self makeConcreteChildOfType:A];
[listOfAllActions addObject:newAction];
[newAction setOwner:self];
[newAction doYourThing];
}
// And similarly for other "performAction..." methods
Each action, then, sends a simple "all done!" message to its owner when it completes:
#interface AbstractChild
#property (weak) Factory * owner;
//...
#implementation AbstractChild
#synthesize owner;
- (void)cleanupAfterCompletion
{
// Subclasses can override this to do more cleanup
// Message the action's owner, passing self so it knows which action
[[self owner] actionHasCompleted:self];
}
Then, back in Factory,
- (void)actionHasCompleted: (AbstractAction *)action
{
// Other cleanup if necessary
// Delete action
[listOfAllActions removeObjectIdenticalTo:action];
}
If for some reason you dislike the action having a direct pointer back to the factory, you could use notifications, but those are generally for times when the two objects have a much weaker relationship than this.
*That's the reality of the situation -- you are creating multiple objects. In fact, to be frank, your idea of having one property for potentially multiple objects seems messy to me.

Here is a article that might be a solution to what you are trying to do... It is basically saying to use the weak qualifier which automatically sets the object to nil if its reference zeroes...
http://thinkvitamin.com/code/ios/ios-5-automatic-reference-counting-arc/ (Credit goes to author of this article)

Related

Are subclass properties preserved if I assign a subclass instance to a property typed as a parent class?

I have a feed that loads a array of:
•Status objects
•PhotoStatus objects - a subclass of Status
When a user clicks on a status in the feed it takes them to ViewCommentsViewController which has the following property that MUST be set in order for the view controller to work:
#property (nonatomic,strong) Status *status;
If I pass/assign:
ViewCommentsViewController.status=photoStatus;
Can I reliably still preserve the subclass properties of the photoStatus some how? Maybe by doing something like photoStatus *revertedPhotoStatus=status; in my view controller, or what is the right way to do what im trying to do? I dont want to have multiple view controller classes, and I don't want to go the sloppy route of having both photoStatus & status properties in my ViewCommentsViewController, so how do I reliably allow the loading of multiple types of content that are all subclasses of Status?
Can I reliably still preserve the subclass properties of the photoStatus some how
Yes, this just happens automatically. It's called polymorphism: a thing is the thing it is, not the thing you happen to type it as. So if you assign an actual PhotoStatus object to a variable typed as a Status, it remains a PhotoStatus under the hood. This mechanism is absolutely crucial; without it, subclass instances would not be very useful!
Note, however, that in order to treat your Status-typed object as a PhotoStatus object, if that is what it really is under the hood, you will need to cast it down to a PhotoStatus object. And if you do this and this happens not to be a PhotoStatus object, you may be heading for a crash later when a PhotoStatus message is sent to an object that is not in fact a PhotoStatus.
In the best of all worlds, you wouldn't need to test what kind of class something is. Instead, the class receiving the object would declare a pointer to a base class that implemented all necessary methods.
The implementations would be different but, in this case, a ViewCommentsViewController could make consistent calls to any kind of Status and know that the methods existed.
Another way of structuring things to assure this would be by using a protocol. That would make your declaration something like #property (nonatomic,strong) id<StatusProvider> status;.
I've typed isKindOfClass far too often to present myself as any kind of purist, but it's nice to use a clean approach when possible.
If you intend to use methods that are defined in the Status class but not PhotoStatus, you need to check the class of the returned object. To do this, you would normally do something along these lines:
Status *status = viewCommentsViewController.status;
if ([[status class] isSubclassOfClass: [PhotoStatus class]])
{
PhotoStatus *photoStatus = (PhotoStatus *) status;
// Handle photoStatus.
}
else
{
// Handle the other case.
}
If you want to save a few lines at the call site, you could add accessors like this:
#implementation Status
- (PhotoStatus *) asPhotoStatus
{
return nil;
}
#end
#implementation PhotoStatus
- (PhotoStatus *) asPhotoStatus
{
return self;
}
#end
and then just call
[[viewCommentsViewController.status asPhotoStatus] doSomething];
Edit: Since Xcode 4.2, sending a message to nil should always return a zero value or cause the returned struct to be filled with zeros. (Unfortunately I couldn't find a specification, but this blog post contains a summary.)

Unable to access App Delegate property

I'm trying to access a property in my app delegate from another class (something I thought would be rather simply) but I'm having troubles in doing so. My files currently look like this:
LTAppDelegate.h
#import <Cocoa/Cocoa.h>
#import "Subject.h"
#interface LTAppDelegate : NSObject <NSApplicationDelegate, NSOutlineViewDelegate, NSOutlineViewDataSource, NSMenuDelegate> {
}
#property Subject *selectedSubject;
#end
LTAppDelegate.m
#synthesize selectedSubject;
The value for selectedSubject is then set inside applicationDidFinishLaunchingin LTAppDelegate.m. Now I'm wanting to get access to this from another class that I have, which is called LTTableViewController and is setup like so:
LTTableViewController.h
#import <Foundation/Foundation.h>
#import "LTAppDelegate.h"
#import "Subject.h"
#import "Note.h"
#interface LTTableViewController : NSObject{
NSMutableArray *notesArray;
LTAppDelegate *appDelegate;
Subject *s;
}
-(IBAction)currentSubjectDetails:(id)sender;
#end
LTTableViewController.m
#import "LTTableViewController.h"
#implementation LTTableViewController
- (id)init
{
self = [super init];
if (self) {
appDelegate = ((LTAppDelegate *)[[NSApplication sharedApplication] delegate]);
s = [appDelegate selectedSubject];
NSLog(#"Test Subject: %#", [s title]);
}
return self;
}
-(IBAction)currentSubjectDetails:(id)sender{
NSLog(#"Selected Subject: %#", [s title]);
}
After inserting various NSLog() messages it would appear that the init method of LTTableViewController is called before applicationDidFinishLaunchingis called in LTAppDelegate. Based on that it makes sense that the "Test Subject" NSLog() in LTTableViewController.m init displays null; however, the 'currentSubjectDetails' method is linked to a button on the interface and when that is pressed after the app is finished loading, the NSLog() message still returns null.
Is there anything obvious I'm missing here. I feel like I'm being a little stupid and missing something really basic.
Similar issue is described here http://iphonedevsdk.com/forum/iphone-sdk-development/11537-viewcontroller-called-before-applicationdidfinishlaunching.html Adding this kind of functionality in the constructor is usually not recommended. Generally, I'd suggest using parameters and not relying on hidden dependencies as those will necessarily depend on the order of execution and you lose the help of the compiler to avoid invalid values. View controller initializers should not be used to store mutable references since view controllers are initialized automatically by predefined constructors, and you cannot pass parameters to them this way.
If you need to access the app delegate, then obtain it, perform operations on it and drop the reference. Try not to cache it, you'll very likely introduce hidden issues. I suggest you hook into the appear-disappear cycle if the viewed contents depend on any kind of current state.
Well, s does not exist, since it is set to null in init, so -currentSubjectDetails prints null. It is not a good idea to set your private variables in the constructor if they depend on other objects.
Rather, let the other objects explicitly tell your controller that it should use that Subject (e.g., treat s as a property).
Or, just query ((LTAppDelegate *)[[NSApplication sharedApplication] delegate]); every time.
-applicationDidFinishLaunching called when e.g. all nib's object initialized, so launching will be ended after construction of views related stuff. This means that constructors of nib's objects wouldn't use any other nib's objects (your delegate and controller initializing with nib, right?).
Try to use -awakeFromNib instead of constructors, I think it will called after construction of both objects.
If you are trying to avoid often calls of ((LTAppDelegate *)[[NSApplication sharedApplication] delegate]) I'll recommend to pass it as method parameter, in function stack. Cyclic references defense and some flexibility.

Test type of NSNotification

I need to check whether an object is an NSNotification. It is not enough to know if it is a subclass, as I want to differentiate between whether it is an NSNotification or a subclass of NSNotification.
So to elaborate I need to differentiate between the following:
An NSConcreteNotification
A Subclass of NSNotification (But not NSConcreteNotification)
The problem is that NSNotifications are actually NSConcreteNotifications and NSConcreteNotification is a private class so I can't use it to test against.
[object isMemberOfClass: [NSNotification class]] // returns NO in both cases
[object isKindOfClass: [NSNotification class]] // returns YES in both cases
There is no reason to subclass NSNotification the way you're describing. First, NSNotification already carries a userInfo dictionary. You can put any data you want in there. You can use category methods to read and write into that dictionary if you like (I do this all the time). For example, a very common thing I want to do is pass along some object, say the RNMessage. So I create a category that looks like this:
#interface NSNotificationCenter (RNMessage)
- (void)postNotificationName:(NSString *)aName object:(id)anObject message:(RNMessage *)message;
#end
#interface NSNotification (RNMessage)
- (RNMessage *)message;
#end
static NSString * const RNMessageKey = #"message";
#implementation NSNotificationCenter (RNMessage)
- (void)postNotificationName:(NSString *)aName object:(id)anObject message:(RNMessage *)message {
[self postNotificationName:aName object:anObject userInfo:[NSDictionary dictionaryWithObject:message forKey:RNMessageKey];
}
#end
#implementation NSNotification (RNMessage)
- (RNMessage *)message {
return [[self userInfo] objectForKey:RNMessageKey];
}
As #hypercrypt notes, you can also use associated references to attach data to any arbitrary object without creating an ivar, but with NSNotification it's much simpler to use the userInfo dictionary. It's much easier to print notification using NSLog. Easier to serialize them. Easier to copy them. Etc. Associated references are great, but they do add lots of little corner cases that you should avoid if you can get away with it.
That sounds like a really bad idea. When you first receive the notification, you already know what type it is, because it's passed as an explicit argument to a notification callback method. Consider storing the notification as a strongly typed property of another object, or inserting in a dictionary under an appropriate key if you're adding it to a collection, or passing it to other methods that don't preserve the type information to make it easier to identify later.
Creating dependencies on private API (including the names of private classes) will make your code more fragile, and much more likely to break in a future release. Obviously, one of the reasons these classes are private is to make it easier for Apple's engineers to change them as they see fit. For example, the concrete subclasses used by NSArray and NSMutableArray just changed in a recent release of the SDK.
To test id object is an NSNotification use:
[object isMemberOfClass:[NSNotification class]];`
To test if it is a NSConcreteNotifications use
[object isMemberOfClass:NSClassFromString(#"NSConcreteNotifications")];
Change the string to the name of a different class as needed...
You can then combine the two check for 'A Subclass of NSNotification (But not NSConcreteNotification'.
Either:
if ([object isMemberOfClass:NSClassFromString(#"NSConcreteNotifications")])
{
// It's a NSConcreteNotifications...
}
else if ([object isKindOfClass:[NSNotification class]])
{
// It's an NSNotification (or subclass) but not an NSConcreteNotifications
}
Or
if ([object isKindOfClass:[NSNotification class]] && ![object isMemberOfClass:NSClassFromString(#"NSConcreteNotifications")])
{ /* ... */ }
If you want to add properties to NSNotifications you should look into Associative References.
The basic idea is:
static const char objectKey;
- (id)object
{
return objc_getAssociatedObject(self, &objectKey);
}
- (void)setObject:(id)object
{
objc_setAssociatedObject(self, &objectKey, object, OBJC_ASSOCIATION_RETAIN);
}
As others have pointed out, it is a bad idea to rely on the name of a private class. If you are looking for one specific subclass, you could just explicitly check for that class.
[notification isMemberOfClass:[MyNotificationSubclass class]];
You could use multiple statements to check for multiple subclasses, but that would be a little cluttered. This method also requires changes every time you add a new class to look for. It may be better to define a readonly property which indicates whether a notification supports the feature you are looking for, so you aren't relying on the class so much as the ability of the class. You could use a category on NSNotification which simply returns NO for this property, and any subclasses which have the feature would override the method to return YES.
#interface NSNotification (MyFeature)
#property (readonly) BOOL hasMyFeature;
#end
#implementation NSNotification (MyFeature)
- (BOOL)hasMyFeature {
return NO;
}
#end
In the subclasses which support it:
- (BOOL)hasMyFeature {
return YES;
}
- (void)performMyFeature {
...
}
This would also allow you to change whether or not a notification has the feature enabled by changing a flag which is returned for hasMyFeature, and your checking code would simply be:
if(notification.hasMyFeature) [notification performMyFeature];

Singleton NSMutableArray accessed by NSArrayController in multiple NIB's

Early warning - code sample a little long...
I have a singleton NSMutableArray that can be accessed from anywhere within my application. I want to be able to reference the NSMutableArray from multiple NIB files but bind to UI elements via NSArrayController objects. Initial creation is not a problem. I can reference the singleton NSMutableArray when the NIB gets loaded and everything appears fine.
However, changing the NSMutableArray by adding or removing objects does not kick off KVO to update the NSArrayController instances. I realize that "changing behind the controller's back" is considered a no-go part of Cocoa-land, but I don't see any other way of programmatically updating the NSMutableArray and letting every NSArrayController be notified (except it doesn't work of course...).
I have simplified classes below to explain.
Simplified singleton class header:
#interface MyGlobals : NSObject {
NSMutableArray * globalArray;
}
#property (nonatomic, retain) NSMutableArray * globalArray;
Simplified singleton method:
static MyGlobals *sharedMyGlobals = nil;
#implementation MyGlobals
#synthesize globalArray;
+(MyGlobals*)sharedDataManager {
#synchronized(self) {
if (sharedMyGlobals == nil)
[[[self alloc] init] autorelease];
}
return sharedMyGlobals;
}
-(id) init {
if(self = [super init]) {
self.globals = [[NSMutableArray alloc] init];
}
return self
}
// ---- allocWithZone, copyWithZone etc clipped from example ----
In this simplified example the header and model for objects in the array:
Header file:
#interface MyModel : NSObject {
NSInteger myId;
NSString * myName;
}
#property (readwrite) NSInteger myId;
#property (readwrite, copy) NSString * myName;
-(id)initWithObjectId:(NSInteger)newId objectName:(NSString *)newName;
#end
Method file:
#implementation MyModel
#synthesize myId;
#synthesize myName;
-(id)init {
[super init];
myName = #"New Object Name";
myId = 0;
return self;
}
#end
Now imagine two NIB files with appropriate NSArrayController instances. We'll call them myArrayControllerInNibOne and myArrayControllerInNib2. Each array controller in the init of the NIB controller sets the content of the array:
// In NIB one init
[myArrayControllerInNibOne setContent: [[MyGlobals sharedMyGlobals].globalArray];
// In NIB two init
[myArrayControllerInNibTwo setContent: [[MyGlobals sharedMyGlobals].globalArray];
When each NIB initializes the NSArrayController binds correctly to the shared array and I can see the array content in the UI as you would expect. I have a separate background thread that updates the global array when content changes based on an external event. When objects need to be added in this background thread, I simply add them to the array as follows:
[[[MyGlobals sharedMyGlobals].globalArray] addObject:theNewObject];
This is where things fall apart. I can't call a willChangeValueForKey and didChangeValueForKey on the global array because the shared instance doesn't have a key value (should I be adding this in the singleton class?)
I could fire off an NSNotification and catch that in the NIB controller and either do a [myArrayControllerInNibOne rearrangeObjects]; or set the content to nil and reassign the content to the array - but both of these seems like hacks and. moreover, setting the NSArrayController to nil and then back to the global array causes a visual flash within the UI as the content is cleared and re-populated.
I know I could add directly to the NSArrayController and the array gets updated, but I don't see a) how the other NSArrayController instances would be updated and b) I don't want to tie my background thread class explicitly to a NIB instance (nor should I have to).
I think the correct approach is to either fire off the KVO notification somehow around the addObject in the background thread, or add something to the object that is being stored in the global array. But I'm at a loss.
As a point of note I am NOT using Core Data.
Any help or assistance would be very much appreciated.
Early warning - answer a little long…
Use objects that model your domain. You have no need for singletons or globals, you need a regular instance of a regular class. What Objects are your storing in your global array? Create a class that represents that part of your model.
If you use an NSMutableArray as storage it should be internal to your class and not visible to outside objects. eg if you are modelling a zoo, don't do
[[[MyGlobals sharedMyGlobals].globalArray] addObject:tomTheZebra];
do do
[doc addAnimal:tomTheZebra];
Dont try to observe a mutable array - you want to observe a to-many property of your object. eg. instead of
[[[MyGlobals sharedMyGlobals].globalArray] addObserver:_controller]
you want
[doc addObserver:_controller forKeyPath:#"animals" options:0 context:nil];
where doc is kvo compliant for the to-many property 'anaimals'.
To make doc kvo compliant you would need to implement these methods (Note - you don't need all these. Some are optional but better for performance)
- (NSArray *)animals;
- (NSUInteger)countOfAnimals;
- (id)objectInAnimalsAtIndex:(NSUInteger)i;
- (id)AnimalsAtIndexes:(NSIndexSet *)ix;
- (void)insertObject:(id)val inAnimalsAtIndex:(NSUInteger)i;
- (void)insertAnimals:atIndexes:(NSIndexSet *)ix;
- (void)removeObjectFromAnimalsAtIndex:(NSUInteger)i;
- (void)removeAnimalsAtIndexes:(NSIndexSet *)ix;
- (void)replaceObjectInAnimalsAtIndex:(NSUInteger)i withObject:(id)val;
- (void)replaceAnimalsAtIndexes:(NSIndexSet *)ix withAnimals:(NSArray *)vals;
Ok, that looks pretty scary but it's not that bad, like i said you don't need them all. See here. These methods dont need to be part of the interface to your model, you could just add:-
- (void)addAnimal:(id)val;
- (void)removeAnimal:(id)val;
and write them in terms of the kvc accessors. The key point is it's not the array that sends notifications when it is changed, the array is just the storage behind the scenes, it is your model class that send the notifications that objects have been added or removed.
You may need to restructure your app. You may need to forget about NSArrayController altogether.
Aaaaaannnnnyyywaaayyy… all this gets you nothing if you do this
[[[MyGlobals sharedMyGlobals].globalArray] addObject:theNewObject];
or this
[doc addAnimal:tomTheZebra];
from a background thread. You can't do this. NSMutableArray isn't thread safe. If it seems to work then the best that will happen is that the kvo/binding notification is delivered on the background as well, meaning that you will try to update your GUI on the background, which you absolutely cannot do. Making the array static does not help in any way i'm afraid - you must come up with a strategy for this.. the simplest way is performSelectorOnMainThread but beyond that is another question entirely. Threading is hard.
And about that static array - just stop using static, you don't need it. Not because you have 2 nibs, 2 windows or anything. You have an instance that represents your model and pass a pointer to that to you viewControllers, windowControllers, whatever. Not having singletons/static variables helps enormously with testing, which of course you should be doing.

iPhone SDK: Accessing methods in other classes

In my iPhone application I have multiple class files, I have my main application's class files, then I have my UIView class files. I have a simple -(void) method declared in my UIView class files, how can I access it from my main applications class files?
A bit more detail: In my application a video is played, when this video finishes playing a notification is sent and actions are preformed, which I have already successfully set up, however when the movie finishes I would like a method declared in another class file to be preformed. If the method was declared in the same class file I would simply use this code: [self mySimpleVoidMethod]; But obviously this doesn't work If the method is declared in a different class file. I believe it is possible to access a method declared in a different class file, but I just haven't got a clue about how to do it. Sorry if I'm using completely incorrect terms to name things. But I am relatively new to programming all together.
You've got a couple of options, depending on your setup. Here are a few:
1) Add a reference to the class with the function (the callee) as a property in the caller's class:
Caller.h
#interface Caller : SomeObject {
Callee *myCallee;
...
}
#property(nonatomic, retain) Callee *myCallee;
Caller.m
#synthesize myCallee;
-(void)someAction {
[myCallee doSomething];
}
Something that sets up Caller after initializing both classes:
caller.myCallee = callee;
2) Use another notification event, like it looks like you already know how to do.
3) Use a protocol if you've got a bunch of different classes that Caller might need to call that all support the same method:
DoesSomething.h
#protocol DoesSomething
-(void)doSomething;
#end
Callee.h
#interface Callee : NSObject<DoesSomething> { // NSObject or whatever you're using...
...
}
-(void)doSomething;
Caller.h
#interface Caller : SomeObject {
id<DoesSomething> *myCallee;
...
}
#property(nonatomic, retain) id<DoesSomething> *myCallee;
... Then as per example 1.
4) Use performSelector to send a message to the class.
Caller.h
#interface Caller : NSObject {
SEL action;
id callee;
}
-(void)setupCallbackFor:(id)target action:(SEL)callback;
Caller.m
-(void)setupCallbackFor:(id)target action:(SEL)callback {
callee = target;
action = callback;
}
-(void)someAction {
if([callee respondsToSelector:action]) {
[callee performSelector:action];
}
I'm sure there are other ways, and there are pros and cons to each of these, but something in there should fit your needs and/or give you enough to scan the documentation to fill in any gaps...
I did a blog post a few weeks ago that outlines one way to do this. It is similar to the previous answers, and includes some sample code you can download and look at. It is based on using table view controllers, but you should be able to adapt the ideas to your application without too much difficulty.
Passing values and messages between views on iPhone
You'll need an instance of the other class, accessible from the code that runs when the movie finishes. Often, this is accomplished by storing an instance of the other class as a field in the class, set either via a "setter", or during construction. You could also use key-value observing, watching a key representing the playstate of the movie; an instance of the other class can register to observe the changes to this key.
Specifically for patterns using UIView, your UIViewController for the view will have access to it (through the view method). If your "main application's class files" have a pointer to the controller - which they probably will, setup via Interface Builder - then that's an easy way to get to a UIView instance.