Как инициализировать глобальность CMMotionManager для использования различными классами? - PullRequest
0 голосов
/ 16 декабря 2011

Я пытаюсь инициализировать диспетчер движения устройства в классе, который содержит все мои глобальные переменные для использования в разных классах. Однако я не могу заставить это работать.

У меня есть это в моем глобальном классе:

// Motion Manager
CMMotionManager *motionManager;

Затем установите свойство в другом заголовочном файле класса:

@property (retain) CMMotionManager *motionManager;

И на .m файле я синтезирую и запускаю обновления:

@synthesize motionManager;

motionManager = [[CMMotionManager alloc] init];

if (motionManager.deviceMotionAvailable) 
    {
        motionManager.deviceMotionUpdateInterval = 1.0/100.0;
        [motionManager startDeviceMotionUpdates];
        NSLog(@"Device Started");

    }

Но когда я позвоню в третий класс:

motionManager.deviceMotionAvailable

Возвращает НЕТ.

PD: оба класса импортируют глобальный класс, а третий класс импортирует заголовок второго.

Ответы [ 2 ]

0 голосов
/ 10 февраля 2012

В каждом приложении iOS уже есть одноэлементный класс, и обычно он называется AppDelegate :-) Это потому, что AppDelegate технически реализует UIApplicationDelegate.

Итак, я последовал этому предложению Джонатана Хуэя , и оно прекрасно работает для меня.

Надеюсь, это поможет, и еще не поздно ответить ..

0 голосов
/ 28 декабря 2011

Хорошо. Кажется, я могу использовать одноэлементный класс для достижения этого:

h файл:

//
//  MotionManagerSingleton.h
//  Air Interface
//
//  Created by MacBook on 11/12/28.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//  File created using Singleton XCode Template by Mugunth Kumar (http://blog.mugunthkumar.com)
//  More information about this template on the post http://mk.sg/89
//  Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above

#import <Foundation/Foundation.h>
#import <CoreMotion/CoreMotion.h>

@interface MotionManagerSingleton : NSObject

+ (MotionManagerSingleton*) sharedInstance;

- (void)startMotionManager;
- (CMAcceleration)getCurrentAcceleration;
- (CMAttitude*)getCurrentAttitude;
- (CMAttitude*)getStartingAttitude;
- (void)setStartingAttitude: (CMAttitude*) ref;
- (bool)isDeviceReady;
- (void)destroyMotionManager;
- (NSTimeInterval) getStamp;



@end

m файл:

//
//  MotionManagerSingleton.m
//  Air Interface
//
//  Created by MacBook on 11/12/28.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//  File created using Singleton XCode Template by Mugunth Kumar (http://blog.mugunthkumar.com)
//  More information about this template on the post http://mk.sg/89    
//  Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above

#import "MotionManagerSingleton.h"



@implementation MotionManagerSingleton

CMMotionManager *motionManager;
CMAttitude *referenceAttitude;
bool initialized;

#pragma mark -
#pragma mark Singleton Methods

+ (MotionManagerSingleton*)sharedInstance {

    static MotionManagerSingleton *_sharedInstance;
    if(!_sharedInstance) {
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
            _sharedInstance = [[super allocWithZone:nil] init];
            });
        }

        return _sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {    

    return [self sharedInstance];
}


- (id)copyWithZone:(NSZone *)zone {
    return self;    
}

#if (!__has_feature(objc_arc))

- (id)retain {  

    return self;    
}

- (unsigned)retainCount {
    return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release {
    //do nothing
}

- (id)autorelease {

    return self;    
}
#endif

#pragma mark -
#pragma mark Custom Methods

// Add your custom methods here
- (void)startMotionManager{
    if (!initialized) {
        motionManager = [[CMMotionManager alloc] init];
        if (motionManager.deviceMotionAvailable) {
            motionManager.deviceMotionUpdateInterval = 1.0/70.0;
            [motionManager startDeviceMotionUpdates];
            NSLog(@"Device Motion Manager Started");
            initialized = YES;
        }
    }
}
- (CMAcceleration)getCurrentAcceleration{
    return motionManager.deviceMotion.userAcceleration;
}
- (CMAttitude*)getCurrentAttitude{
    return motionManager.deviceMotion.attitude;
}
- (CMAttitude*)getStartingAttitude{
    return referenceAttitude;
}
- (float)getInterval{
    return motionManager.accelerometerUpdateInterval;
}
- (NSTimeInterval) getStamp{
    return motionManager.deviceMotion.timestamp;
}
- (void)setStartingAttitude: (CMAttitude*) ref{
    referenceAttitude = motionManager.deviceMotion.attitude;
}
- (bool)isDeviceReady{
    return motionManager.deviceMotionActive;
}
- (void)destroyMotionManager{
    [motionManager stopDeviceMotionUpdates];
    motionManager = nil;
}

@end

и всякий раз, когда я хочучтобы использовать его, я могу просто объявить переменную в заголовке этого класса следующим образом:

MotionManagerSingleton *Manager;

и использовать это так в файле m:

Manager = [MotionManagerSingleton sharedInstance];

if ([Manager isDeviceReady]) {
    NSLog(@"Device Is Ready on Drawing View Controller");
}

referenceAttitude = [Manager getStartingAttitude];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...