如何使我的应用记住整数?

问题描述

| 在我的一个ViewController中,我设置了一个整数及其相等的值。我正在尝试将此整数放入更高版本的ViewController中的NSLog中,以查看是否记住它,并认为它是0,但不是。我是编程新手,所以我很困惑。我没有释放整数,我想也许可以做到这一点。我该怎么办?! 更新: int位于StarsViewController.h,StarsViewController.m和StepOne.m中。 StarsViewController.h
#import <UIKit/UIKit.h>

@interface StarsViewController : UIViewController {
int typeofstar;
}

@property (nonatomic) int typeofstar;
@end
StarsViewController.m
#import \"StarsViewController.h\"
#import \"StepOne.h\"

@implementation StarsViewController
@synthesize typeofstar;


#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
typeofstar = 1;
NSLog(@\"%i\",typeofstar);
}


- (IBAction)proceed {
StepOne *one = [[[StepOne alloc] initWithNibName:@\"StepOne\" bundle:nil] autorelease];
// you can change flip horizontal to many different other transition styles.
one.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:one animated:YES];
}

@end
StepOne.m
// I only included the important part:
- (void)viewDidLoad
{
    [super viewDidLoad];
    StarsViewController *type = [[StarsViewController alloc] autorelease];
    NSLog(@\"%i\",type.typeofstar);
}
    

解决方法

对于单例或数据类,我认为这将是您的最佳解决方案。您可以在单例类中声明一个变量,然后在应用程序中的任何位置访问它。这样,变量的值(在您的情况下为整数)将得以保留。 这是单例/数据类的工作方式: //DataClass.h
@interface DataClass : NSObject {    

int i;   

}    
@property(nonatomic,assign)int i;    
+(DataClass*)getInstance;    
@end  
//DataClass.m
@implementation DataClass    
@synthesize i;    
static DataClass *instance =nil;    
+(DataClass *)getInstance    
{    
    @synchronized(self)    
    {    
        if(instance==nil)    
    {    

        instance= [DataClass new];    
    }    
}    
return instance;    
}    
现在,在您的视图控制器中,您需要将该方法调用为:
DataClass *obj=[DataClass getInstance];  
obj.i= // whatever you want;  
每个视图控制器都可以访问此变量。您只需要创建一个Data类的实例。     ,也许问题在于您永远不会初始化
StarsViewController
实例。尝试以下方法:
StarsViewController *type = [[[StarsViewController alloc] initWithNibName: @\"StarsView\" bundle: nil] autorelease];
另外,参考Firoze的答案,每个星型视图控制器将具有自己的
type
ivar。如果要使用全局类型,请查看静态变量或
NSUserDefaults
。     ,
StarsViewController *type = [[StarsViewController alloc] autorelease];
此行(上方)创建StarsViewController的实例。这个实例与您刚来自的其他StarsViewController不同(相同的对象)。 因此,这个新的StarsViewController实例具有自己的\'typeofstar \',其初始值为零。 那有意义吗? 编辑: 如何解决这个问题: 好吧,您可以将事情直接从一个视图控制器传递到另一个。您可以在StepOne视图控制器上创建一个属性,该属性可以在呈现该属性之前设置。实际上,如果您正在研究如何在StepOne视图控制器上设置modalTransitionStyle,则实际上您正在这样做。那是财产。您可以创建另一个名为\“ typeOfStar \”的属性,并以相同的方式进行设置。 您还有许多其他选项可以共享数据。当您的应用程序运行时,您必须将其视为在任何给定时间都在内存中的大量对象。您的应用程序委托是一个很容易从任何地方访问的对象,因此人们确实使用它来存储他们想在整个应用程序中使用的小东西。 您可以将全局变量视为另一种选择。 (明智地使用!) 随着需求变得越来越复杂,您可能会留下其他对象,这些对象以单例形式存在或悬而未决。 希望能有所帮助。