Q1:我可以调用一个方法并让它从另一个当前正在主线程上执行的方法内部在后台线程上执行吗?
Q2:作为上述的扩展,我可以调用一个方法并让它从另一个当前正在其他后台线程本身上执行的方法内部在后台线程上执行吗?
Q3:最后一个问题是:如果我在某个线程(主/后台)上初始化某个对象 X 的一个实例,然后在某个其他后台线程上执行该对象 X 的方法 Y,这个方法 Y 可以吗?发送消息并更新一个int property
(例如那个对象 X,或者这样的通信是不可能的?
我问最后一个问题的原因是因为我一遍又一遍地重复它,我不知道这里出了什么问题:
以下代码返回零加速度和零度值:
运动处理器.m
@implementation MotionHandler
@synthesize currentAccelerationOnYaxis; // this is a double
-(void)startCompassUpdates
{
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate=self;
[locationManager startUpdatingHeading];
NSLog(@"compass updates initialized");
}
-(int) currentDegrees
{
return (int)locationManager.heading.magneticHeading;
}
-(void) startAccelerationUpdates
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
self.currentAccelerationOnYaxis = motion.userAcceleration.y;
}
];
}
@end
测试者.m
@implementation Tester
-(void)test
{
MotionHandler *currentMotionHandler = [[MotionHandler alloc] init];
[currentMotionHandler performSelectorInBackground:@selector(startCompassUpdates) withObject:nil];
[currentMotionHandler performSelectorInBackground:@selector(startAccelerationUpdates) withObject:nil];
while(1==1)
{
NSLog(@"current acceleration is %f", currentMotionHandler.currentAccelerationOnYaxis);
NSLog(@"current degrees are %i", [currentMotionHandler currentDegrees]);
}
SomeViewController.m
@implementation SomeViewController
-(void) viewDidLoad
{
[myTester performSelectorInBackground:@selector(test) withObject:nil];
}
@end
但是,以下代码通常会返回这些值:
测试者.m
@interface Tester()
{
CLLocationManager *locationManager;
double accelerationOnYaxis;
// more code..
}
@end
@implementation Tester
- (id) init
{
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate=self;
[locationManager startUpdatingHeading];
// more code..
}
-(void) test
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
accelerationOnYaxis = motion.userAcceleration.y;
}
];
while(1==1)
{
NSLog(@"current acceleration is %f", accelerationOnYaxis);
NSLog(@"current degrees are %i", locationManager.heading.magneticHeading);
}
}
SomeViewController.m
@implementation SomeViewController
-(void) viewDidLoad
{
[myTester performSelectorInBackground:@selector(test) withObject:nil];
}
第一个版本有什么问题?我真的很想使用第一个,因为它在设计方面似乎要好得多。谢谢您的帮助!