2016-08-01 35 views

回答

0

首先,你需要创建过NSObject类

给类名GlobalShareClass

GlobalShareClass.h

#import <Foundation/Foundation.h> 
@interface GlobalShareClass : NSObject 
{ 
} 
@property (nonatomic) float xvalue 
@property (nonatomic) float yvalue 
+ (GlobalShareClass *)sharedInstance; 
@end 

GlobalShareClas.m

#import "GlobalShareClass.h" 
static GlobalShareClass *_shareInstane; 
@implementation GlobalShareClass 
@synthesize xvalue; 
@synthesize yvalue; 

+ (GlobalShareClass *)sharedInstance 
{ 
    if (_shareInstane == nil) 
    { 
     _shareInstane = [[GlobalShareClass alloc] init]; 
    } 
    return _shareInstane; 
} 

ViewController.h

#import <UIKit/UIKit.h> 
#import "GlobalShareClass.h" 

@interface ViewController : UIViewController 
{ 
    GlobalShareClass *globalShare; 
} 
@end; 

ViewController.m

#import "ViewController.h" 
@interface ViewController() 
@end 
@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    globalShare = [GlobalShareClass sharedInstance]; 
    globalShare.xvalue = 50.0; 
    globalShare.xvalue = 100.0; 

} 
0

可能这里使用的正确的东西应该是一个类级别的属性。有关更多信息,请参阅here

1

而不是使用两个浮点数的,我会建议在存储专门为这个制成的容器坐标:CGPoint

要在全球范围内使用它,您可以将其添加到单身人士(如在@ user3182143答案中),或者从您的班级公开它。

在你.m,你可以把它定义为一个常数(既@interface@implementation外)如下:

const CGPoint kMyCoordinate = {.x = 100, .y = 200};

为了其他类能够使用它,你需要公开它在.h如下:

extern const CGPoint kMyCoordinate;

虽然你平时创建CGPointsCGPointMake(x,y)在这个特殊情况下,我们必须使用简写,否则Xcode会抱怨“初始化元素不是编译时常量”。

+0

我认为你的答案是最方便的。我想过使用CGPoint。 –

+0

在我的“.h”我添加@property(nonatomic,分配)CGPoint * lastScrollOffset;并在我的“.m”我必须打电话给他,并分配到当前位置我查看我是如何做猫? –

+0

如果你想使用属性而不是类常量,那么在'.h'中定义属性:'@property(nonatomic)CGPoint myCoordinate;' 而在'.m'中:'self.myCoordinate = CGPointMake(100 ,200);' –