unclear use of @property in window app using core

2019-09-14 10:28发布

Looking through a Window based application ive used to experiment with as a way of getting my head around core data, ive noticed that the appdelegate has the following code

myAppDelegate.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface myAppDelegate : NSObject <UIApplicationDelegate> {


NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;       
NSPersistentStoreCoordinator *persistentStoreCoordinator;

UIWindow *window;
UITabBarController *tabBarController;

}

myAppDelegate.m

#import "myAppDelegate.h"


@interface myAppDelegate (PrivateCoreDataStack)
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@end

@implementation myAppDelegate

@synthesize window, tabBarController;

// code ....

// 
- (NSManagedObjectContext *) managedObjectContext {
}
- (NSManagedObjectModel *)managedObjectModel {
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
}

// etc.....

i want to understand a few things about what this project is doing

  1. why the properties in the category declaration? (if i delete the privateCoreDataStack category everything still works...)
  2. why the properties appear to be linked with the methods in the implementation ... managedObjectContext {} etc
  3. why the members in the .h file have the same name as the properties and the methods
  4. why code completion lets me use dot '.' to access the members but then fails on compilation say it cant find a getter

thanks !

1条回答
我命由我不由天
2楼-- · 2019-09-14 10:57

These are basic concepts in Objective-C, but here's a quick rundown:

Instance members are generally considered to be private, and you should kind of never access the instance members of other objects except through accessors. Hence the need for the

property declarations are like method definitions; @property (…, readonly) NSManagedObjectModel *managedObjectModel; is basically the same as - (NSManagedObjectModel *)managedObjectModel;, except for the fact that it enables dot-notation.

The category is used to hide these accessors from the users of the class (for whatever reason); hence the name PrivateCoreDataStack. The category is the reason dot-notation works; if you remove it, it won't.

As for the names; method names and instance members name live in separate namespaces; meaning that they can have the same name; this is very handy, because it tells you that - (id)somePropery; accesses id someProperty;; or that @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; accesses NSManagedObjectContext *managedObjectContext.

查看更多
登录 后发表回答