属性不会在iOS 7中初始化

我正在开发iOS 7,但我仍然必须手动写getter,否则我的属性不会被初始化。 我尝试手动综合这些属性,即使不再需要这些属性,但是这样做不行。

在我的视图控制器下面,我使用属性motionTracker ,它永远不会被初始化。 我所有的项目都有同样的问题,所以我知道这是我的一个误解。

 #import "ViewController.h" #import "TracksMotion.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIButton *startRecording; @property (weak, nonatomic) IBOutlet UIButton *stopRecording; @property (strong, nonatomic) TracksMotion *motionTracker; @end @implementation ViewController @synthesize motionTracker = _motionTracker; - (void)startMyMotionDetect { [self.motionTracker startsTrackingMotion]; } @end 

motionTracker拥有方法startsTrackingMotion的公共API,所以我不知道为什么这不起作用。

 #import <Foundation/Foundation.h> #import <CoreMotion/CoreMotion.h> @interface TracksMotion : NSObject - (void)startsTrackingMotion; - (void)stopTrackingMotion; @property (strong, nonatomic) CMMotionManager *motionManager; @end 

属性/实例variables不是神奇地为你初始化的。 当你说:

 @property (strong, nonatomic) TracksMotion *motionTracker; 

…您只是为实例variables保留内存空间(并通过@synthesize或autosynthesis生成getter和setter方法)。 在那里没有实际的TracksMotion对象。 你必须编写代码来做到这一点。 您必须创build或获取一个TracksMotion实例,并在某个时候将其分配给self.motionTracker ,大概在自己的生命早期(在这种情况下,这是一个ViewController实例)。 在你运行代码之前, self.motionTracker是零。

(这可能是因为看起来网点自动初始化而感到困惑,例如,你有@property (weak, nonatomic) IBOutlet UIButton *startRecording;当然, self.startRecording是一个button,但这是因为nib加载过程对你来说是我所说的必须做的事情:它从故事板或.xib文件中创build一个button,并将它分配给这个实例variables。)

Interesting Posts