簡體   English   中英

從另一個類檢索變量-目標C

[英]Retrieving variables from another class - Objective C

我正在嘗試從我的類PYTimelineViewControllerrippleMake檢索NSString類型的變量。

這是我在做什么:

在我的rippleMake.m

    /* SET OBJECT */
    PYTimelineViewController *getRippleForVideo = [[PYTimelineViewController alloc] init];
    /* ESTABLISH THE RIPPLE IT VIDEO FOR CHALLENGE VIDEO */
    NSString *videoFor = [getRippleForVideo getchallengeForVideo];
    NSLog(@"%@",videoFor);

運行時, videoFor返回null

在我的PYTimelineViewController.h

@interface PYTimelineViewController : UITableViewController//<MWPhotoBrowserDelegate>

...
@property (nonatomic, strong) NSString *challengeForVideo;
-(NSString *)getchallengeForVideo;
- (void)setchallengeForVideo:(NSString*)challengeforVideo;
@end

在我的PYTimelineViewController.m

-(IBAction)openRippleIt:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    NSInteger rowOfTheCell = (indexPath.row + 1000); // ADD 1000 to get away from effecting other code
    UIButton *button=(UIButton *)[self.view viewWithTag:rowOfTheCell];

    NSString *btnTitle = [button currentTitle];
    [self setchallengeForVideo:btnTitle];
    NSLog(@"%@",[self getchallengeForVideo]); <--- This outputs exactly what I need.
    [self performSegueWithIdentifier:@"moveTorippleIt" sender:self];
}

.m和設置器:

-(void) setchallengeForVideo:(NSString *)challengeforVideo
{
    _challengeForVideo = challengeforVideo;
}
-(NSString *) getchallengeForVideo
{
    return _challengeForVideo;
}

粗略地將用戶推到新的ViewController但這不應該成為問題。

不知道為什么我無法檢索該值,因為似乎所有內容都已正確配置。 特別是我的吸氣劑和吸氣劑。

建議,想法?

[[PYTimelineViewController alloc] init]創建一個新的PYTimelineViewController,並且不提供現有的。

某些代碼未在從另一個ViewController調用的方法中執行

其他一些評論...

如果使用Xcode> = 4.4,則不需要getter和setter。 它們由編譯器自動響應@property

慣用的Objective-C在屬性上不使用“ get”前綴。

“復制”通常是用於字符串的正確屬性屬性,因為它們是可變的。

標頭應如下所示:

@interface PYTimelineViewController : UITableViewController
@property (nonatomic, copy) NSString *challengeForVideo;
@end

用法應如下所示:

PYTimelineViewController *vc = [[PYTimelineViewController alloc] init];
[vc setChallengeForVideo:@"some text"];
NSLog(@"%@", [vc challengeForVideo]);

對於加分,請改為使用點語法:

PYTimelineViewController *vc = [[PYTimelineViewController alloc] init];
vc.challengeForVideo = @"some text";
NSLog(@"%@", vc.challengeForVideo);

如果要從視圖控制器檢索對象,則只需將對象發送到您的類。

當您在rippleMake.m實例化PYTimelineViewController時,這是全新的,因此您可以松開所需對象的引用。

另外, 如果您當時唯一的目標是獲取var的值,則無需實現getter或setter。 @property鍵會為您創建吸氣劑/設置劑。

通過在此對象中添加一個公共屬性 ,將對象傳遞給您的視圖:

// RippleMake.h
// e.g
@property (strong, nonatomic) NSString *foo

在視圖控制器中實例化類時,請確保傳遞屬性:

// ViewController.m
// e.g
RippleMake *ripple = ....
ripple.foo = foo;
...

要將對象傳遞給另一個視圖控制器,您必須執行相同的操作,但是在prepareForSegue:sender方法中,請參見以下答案: https : //stackoverflow.com/a/22867976/1745596

暫無
暫無

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

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