在Objective-C中使用init初始化对象时出现问题

时间:2009-12-18 14:18:46

标签: iphone objective-c

我有一个对象,我通过调用init函数来确定它的属性,它运行正常, 当我试图添加另一个对象并对其进行内部化时,第一个对象没有获得正确的内容,我如何将其初始化为多个具有不同或相同属性的对象?

- (void)viewDidLoad {   
    pic1 = [[peopleAccel alloc] init];
}

班级人员:

- (id) init
{
    self = [super init];
    if (self != nil) {
        position = CGPointMake(100.0, 100.0);
        velocity = CGPointMake(4.0, 4.0);
        radius = 40.0;
        bounce = -0.1f;
        gravity = 0.5f;
        dragging = NO;
        [[UIAccelerometer sharedAccelerometer] setDelegate:self];
        acceleratedGravity = CGPointMake(0.0, gravity);
    }
    return self;
}

2 个答案:

答案 0 :(得分:4)

我发现设置sharedAccelerometer的委托有问题。一次只能有一个对象可以成为另一个对象的委托。因此,您应该只创建一个peopleAccel对象。

编辑:

如果您需要将加速度计事件发送到多个对象,您可以创建一个特定的委托对象,负责接收加速度计事件并通过通知将它们广播给您的几个人的Accel对象。请参阅此问题以获取一些提示:NSNotificationCenter vs delegation?

答案 1 :(得分:1)

创建代理,以便多个对象可以接收加速计事件。

你是否应该这样做或使用NSNotificationCenter是有争议的,有两个阵营,但我个人会使用这种方法。 NSNotificationCenter必须检查字符串名称以识别事件类型;这种方法可能会稍微快一些,特别是通过更多优化。更多的打字但我会说其他人也更容易跟随。

像这样......

/* PLUMBING */
/* in headers */

@protocol MyAccelSubDelegate
-(void)accelerometer:(UIAccelerometer*)accelerometer
  didAccelerate:(UIAcceleration*)acceleration;
@end

@interface MyAccelSubDelegateProxy : NSObject <UIAccelerometerDelegate> {
  NSMutableArray subDelegates;
}
-(id)init;
-dealloc;
-(void)addSubDelegate:(id<MyAccelSubDelegate>)subDelegate;
-(void)removeSubDelegate:(id<MyAccelSubDelegate>)subDelegate;
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
  (UIAcceleration *)acceleration;
@end

/* in .m file */

@implementation MyAccelSubDelegateProxy 
-(id)init { self = [super init];
  if (self!=nil) subDelegates = [[NSMutableArray alloc] init]; return self; }
-dealloc { [subDelegates release]; }
-(void)addSubDelegate:(id<MyAccelSubDelegate>)subDelegate {
  [subDelegates insertObject:subDelegate atIndex:subDelegates.count]; }
-(void)removeSubDelegate:(id<MyAccelSubDelegate>)subDelegate {
  for (int c=0; c < subDelegates.count; c++) { 
    id<MyAccelSubDelegate> item = [subDelegates objectAtIndex:c];
    if (item==subDelegate) { [subDelegates removeObjectAtIndex:c];
      c--; continue; }
  }
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
  (UIAcceleration *)acceleration {
  for (int c=0; c < subDelegates.count; c++)
    [((id<MyAccelSubDelegate>)[subDelegates objectAtIndex:c])
      accelerometer:accelerometer didAccelerate:acceleration];
}
@end

/* SOMEWHERE IN MAIN APPLICATION FLOW STARTUP */
accelProxy = [[MyAccelSubDelegateProxy alloc] init];
[UIAccelerometer sharedAcclerometer].delegate = accelProxy;
[UIAccelerometer sharedAcclerometer].updateInterval = 0.100; // for example

/* TO ADD A SUBDELEGATE */
[accelProxy addSubDelegate:obj];

/* TO REMOVE A SUBDELEGATE */
[accelProxy removeSubDelegate:obj];

/* SOMEWHERE IN MAIN APPLICATION SHUTDOWN */
[UIAccelerometer sharedAcclerometer].delegate = nil;
[accelProxy release];