kakadais
kakadais

Reputation: 491

Casting of [UIApplication sharedApplication].delegate

I've got a test project to use the private data object on several view controller. (I've downloaded it from web & git-hub)

- (ExampleAppDataObject*) theAppDataObject;
{
    id<AppDelegateProtocol> theDelegate = (id<AppDelegateProtocol>) [UIApplication sharedApplication].delegate;
    ExampleAppDataObject* theDataObject;
    theDataObject = (ExampleAppDataObject*) theDelegate.theAppDataObject;
    return theDataObject;
}

First question is, theDelegate was casted with AppDelegateProtocol, even this applications UIApplication delegate name was ViewControllerDataSharingAppDelegate, and there's no warning. I can't under stand why, maybe it's because that was a id type? (AppDelegateProtocol is a custom delegate protocol he declared in the AppDelegate.)

Second, it shows this kind of code on every view controller, and it seems like just a single-ton pattern. I don't think this is not the best way to transfer data between view controller. Which is the best way to transfer object data type?

Thanks.

Upvotes: 0

Views: 1256

Answers (1)

Duncan C
Duncan C

Reputation: 131481

Creating a protocol decouples the code somewhat from the specific implementation. You could conceivably have several applications, each of which uses its own custom class as an app delegate, but all implementations conform to the AppDelegateProtocol.

I used to use the app delegate to hold global data and methods a lot when I first started in iOS.

However, that fills your app delegate with app-specific code.

I've shifted away from that approach recently, and use a data container singleton (and perhaps a utility methods singleton as well.) As is typical for a singleton, I define a class method that lets me fetch the singleton. I add properties to my singleton as needed to store data, and then just use the class method to get a pointer to the singleton. I write my class method to lazy load the singleton.

Its also easy to make your data container singleton persistent by making it conform to NSCoding. Then every time you get moved to the background, just save your singleton somewhere. On app launch, read it in.

Upvotes: 1

Related Questions