问题
I'm developing for iOS 7 but I still have to manually write getters otherwise my properties just don't get initialized. I tried to manually synthesize those properties, even though that shouldn't be needed anymore, but that doesn't do it.
In my view controller below, I use the property motionTracker
, which never gets initialized. I have the same issue with all my projects, so I know it's a misunderstanding on my part.
#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
The motionTracker
has a public API for the method startsTrackingMotion
so I don't know why this doesn't work.
#import <Foundation/Foundation.h>
#import <CoreMotion/CoreMotion.h>
@interface TracksMotion : NSObject
- (void)startsTrackingMotion;
- (void)stopTrackingMotion;
@property (strong, nonatomic) CMMotionManager *motionManager;
@end
回答1:
Properties / instance variables are not magically initialized for you. When you say:
@property (strong, nonatomic) TracksMotion *motionTracker;
... you are just reserving memory space for an instance variable (and generating a getter and a setter method through @synthesize
or autosynthesis). There is no actual TracksMotion object there until you put one there. You must write code to do that. You must create or obtain a TracksMotion instance and assign it to self.motionTracker
at some point, presumably early in the life of self
(in this case, that's a ViewController instance). Until you run code that does that, self.motionTracker
is nil.
(It is possible that you are being confused because it looks like outlets are automatically initialized. For example, you've got @property (weak, nonatomic) IBOutlet UIButton *startRecording;
And sure enough, self.startRecording
is a button. But that's because the nib-loading process does for you the very thing I'm saying you must do: it makes a button from the storyboard or .xib file, and assigns it to this instance variable.)
来源:https://stackoverflow.com/questions/23439563/properties-dont-get-initialized-in-ios-7