簡體   English   中英

如何讓我的應用記住 integer?

[英]How can I make my app remember an integer?

在我的一個 ViewControllers 中,我設置了一個 integer 及其對應的值。 我正在嘗試將這個 integer 放入稍后 ViewController 中的 NSLog 中,看看它是否記得它,它認為它是 0,它不是。 我對編程很陌生,所以我真的很困惑。 我沒有發布 integer,我想也許可以這樣做。 我該怎么辦?!

更新:

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);
}
StarsViewController *type = [[StarsViewController alloc] autorelease];

這一行(上面)創建了一個 StarsViewController 的實例。 這與您剛剛來自的其他 StarsViewController 不同的實例(相同的對象)。

所以這個 StarsViewController 的新實例有它自己的“typeofstar”,它最初是零。

那有意義嗎?

編輯:

如何解決這個問題:

好吧,您可以直接從一個視圖 controller 傳遞東西到另一個視圖。 您可以在 StepOne 視圖 controller 上創建一個屬性,您可以在呈現它之前設置它。 實際上,如果您查看如何在 StepOne 視圖 controller 上設置 modalTransitionStyle,那么您現在正在這樣做。 那是一種財產。 您可以創建另一個名為“typeOfStar”的屬性並以相同的方式設置它。

您還有許多其他共享數據的選項。 當您的應用程序正在運行時,您必須將其視為 memory 在任何給定時間的大量對象。 您的應用程序委托是一個 object,它很容易從任何地方訪問,因此人們確實使用它來存放他們想要在整個應用程序中使用的小東西。

您可以將全局變量視為另一種選擇。 (明智地使用!)

隨着您的需求變得越來越復雜,您可能會保留其他對象作為單例或掛起單例。

希望有幫助。

也許問題在於您從未初始化StarsViewController實例。 嘗試以下方法:

StarsViewController *type = [[[StarsViewController alloc] initWithNibName: @"StarsView" bundle: nil] autorelease];

此外,參考 Firoze 的回答,每個星星視圖 controller 都會有自己的type ivar。 如果您想擁有一個全局類型,請查看 static 變量或NSUserDefaults

選擇singleton數據 class ,我認為這將是您的最佳解決方案。 您可以在 singleton class 中聲明一個變量並在應用程序的任何位置訪問它。 這樣,變量的值(在您的情況下為整數)被保留。
這就是單例/數據 class 的工作方式:

//數據類.h

@interface DataClass : NSObject {    

int i;   

}    
@property(nonatomic,assign)int i;    
+(DataClass*)getInstance;    
@end  

//數據類.m

@implementation DataClass    
@synthesize i;    
static DataClass *instance =nil;    
+(DataClass *)getInstance    
{    
    @synchronized(self)    
    {    
        if(instance==nil)    
    {    

        instance= [DataClass new];    
    }    
}    
return instance;    
}    

現在在您看來 controller 您需要將此方法稱為:

DataClass *obj=[DataClass getInstance];  
obj.i= // whatever you want;  

每個視圖 controller 都可以訪問此變量。 您只需創建數據 class 的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM