我尝试了两种不同的应用程序来测试一些东西。
第一个应用程序简单
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
NSMutableString *text;
}
@property (nonatomic, retain)NSMutableString *text;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize text = text;
- (void)viewDidLoad
{
[super viewDidLoad];
text = @"FOO";
NSLog(@"%@", text);
self.text = @"FOO2";
NSLog(@"%@", self.text);
NSLog(@"1:%@ - 2:%@", text, self.text);
}
这使得事情看起来像是用相同的名称合成,使它们成为相同的变量。因为它打印出来:
2013-09-05 11:20:14.527 testIvar[12965:c07] FOO
2013-09-05 11:20:14.528 testIvar[12965:c07] FOO2
2013-09-05 11:20:14.529 testIvar[12965:c07] 1:FOO2 - 2:FOO2
即使我使用%p打印text和self.text的地址内存我也会得到相同的地址
* 我的其他应用测试是*
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSManagedObjectContext *managedObjectContext;
NSManagedObjectModel *managedObjectModel;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@property ( strong, nonatomic ) UINavigationController *navigationController;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "MasterViewController.h"
@implementation AppDelegate
@synthesize managedObjectContext = managedObjectContext;
@synthesize managedObjectModel = managedObjectModel;
@synthesize persistentStoreCoordinator = persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
MasterViewController *masterVC = [[MasterViewController alloc]initWithNibName:@"MasterViewController" bundle:nil];
masterVC.MOC = managedObjectContext;
self.navigationController = [[UINavigationController alloc]initWithRootViewController:masterVC];
[self.window setRootViewController:self.navigationController];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
如果我这样做,这个应用程序将不起作用
masterVC.MOC = managedObjectContext;
但只有在我这样做才有效
masterVC.MOC = self.managedObjectContext;
即使我打印了managedObjectContext和self.managedObjectContext的mem地址 我得到2个不同的地址
怎么可能?同样的东西在2个不同的应用程序中,表现为2种不同的方式?!?!?!?!?!?!?!?!?
答案 0 :(得分:1)
masterVC.MOC = self.managedObjectContext;
只能起作用,因为在这种情况下已经覆盖了getter方法。
仔细查看,您会发现在AppDelegate中有一个方法
- (NSManagedObjectContext *)managedObjectContext
当您通过self引用对象时,将调用重写的getter方法。