Can you access application delegate from within a UITableViewDataSource function?

后端 未结 4 1945
余生分开走
余生分开走 2021-01-01 09:42

I\'m trying to figure out the SQLite functionality for the iPhone, and I\'m having some problems reading my database file from an overridden UITableViewDataSource function.

相关标签:
4条回答
  • 2021-01-01 10:00

    Roger is correct, but I personally find it extremely confusing to mix dot syntax and bracket syntax in the same statement.

    If this confuses you as well, the equivalent syntax, using only bracket notation, is:

    [[UIApplication sharedApplication] delegate];
    

    and yes, you may need to cast the result to be your application delegate class, rather than the generic UIApplicationDelegate class, or you will get a number of compiler warnings, most likely.

    0 讨论(0)
  • 2021-01-01 10:15

    The Application is a singleton which maintains a reference to the app delegate. You can always access your app delegate using:

    [UIApplication sharedApplication].delegate
    

    You may need to cast the return to your own app delegate class to get rid of warnings. Even better, write an accessor that returns your upcast app delegate:

    #pragma mark access to app delegate etc.
    + (MyAppDelegateClass*) sharedAppDelegate; {
        return (MyAppDelegateClass*)[[UIApplication sharedApplication] delegate];
    }
    
    0 讨论(0)
  • 2021-01-01 10:22

    The problem turned out to be really simple. I had created the NSString to hold the path to my database file using stringByAppendingPathComponent: . I failed to realize that this was going to be autoreleased, and so I didn't bother to explicitly retain it. That reason it was returning a different type of object was because that memory had been reused once the string had been autoreleased.

    Explicitly retaining the string holding the path to the database file solved the problem.

    0 讨论(0)
  • 2021-01-01 10:26

    While I don't like sticking too much into my AppDelegate, I'll often need to access it to get to other singletons in my app, which makes the method call + cast a little cumbersome. So in most of my apps, I'll define a quick macro in my global header file.

    Example follows:

    
    #define MY_DELEGATE (AppDelegate*)[[UIApplication sharedApplication] delegate]
    

    It's a lot easier to refer to MY_DELEGATE.

    0 讨论(0)
提交回复
热议问题