开发者社区> 问答> 正文

在objective-c中使用全局/静态变量

保存用作方法的变量,然后在另一个方法中调用。
实现时会不会用到全局/外部/静态变量?如果需要应该怎么用?

我试过用全局和静态,但是都失败了。

代码中用来保存newX 和 newY 的信息。

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
...
    int newX = (int)(Button.center.x + valueX);
    int newY = (int)(Button.center.y + valueY);
...
}

然后在这里调用:

-(IBAction)clicked:(id)sender

{
    randX = arc4random() % 320;
    randY = arc4random() % 548;

    CGPoint randNewPlace = CGPointMake(randX, randY);
    Rand.center = randNewPlace;
    if (newX == randX || newY  == randY)
    {
        [Rand sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
}

展开
收起
爵霸 2016-03-24 09:53:04 2044 0
1 条回答
写回答
取消 提交回答
  • 你是做Android转iOS的么?在Objc中没有Java里全局变量的这个概念,只能够通过单例实现类似的效果。
    创建一个GloubVariables对象保存需要保存的内容:

    //////////////////////////////////////////////////////////////////////////
    GloubVariables.h
    @interface GloubVariables : NSObject
    {
        int newX;
        int newY;
    }
    
    @property(assin,nonatomic) int newX;
    @property(assin,nonatomic) int newY;
    +(GloubVariables *)sharedInstance;
    
    @end
    //////////////////////////////////////////////////////////////////////////
    GloubVariables.m
    #import "GloubVariables.h"
    @implementation GloubVariables
    @synthesize newX;
    @synthesize newY;
    
    static GloubVariables *instance_;
    +(GloubVariables *)sharedInstance
    {
        @synchronized(self)
        {
            if(instance_ == nil)
            {
                instance_ = [[GloubVariables alloc] init];
            }
        }
        return instance_;
    }
    @end
    //////////////////////////////////////////////////////////////////////////

    然后需要用到的地方:

    [GloubVariables sharedInstance].newX
    [GloubVariables sharedInstance].newY
    2019-07-17 19:11:59
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载