我在我的CRHViewControllerScript类中创建了一个名为“bulletedArray”的NSArray,并试图访问相同的数组,并将其写入到我的CRHCommentSection类的NSLog中。但是,它不写入数组。我知道这个数组可以工作,并可以在第一课中写出来。我认为我的下一课的方法很糟糕,但这里是我的代码的样子。无法在我的其他视图控制器中访问我的阵列
“CRHViewControllerScript.h”
@interface CRHViewControllerScript : UIViewController <UITextViewDelegate> {
__weak IBOutlet UITextView *myTextView;
}
+ (NSArray*)theArray;
- (IBAction)chalkYes:(id)sender;
@end
“CRHViewControllerScript.m”
#import "CRHViewControllerScript.h"
static NSArray* bulletedArray = nil;
@interface CRHViewControllerScript()
@end
@implementation CRHViewControllerScript
+ (NSArray*)theArray {
return bulletedArray;
}
- (IBAction)chalkYes:(id)sender {
//get the text inside the textView
NSString *textContents = myTextView.text;
textContents = [textContents stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//make the array
NSArray *bulletedArray = [textContents componentsSeparatedByString:@"\u2022"];
//eliminate blank component at top of the array ("")
NSUInteger len = bulletedArray.count;
if (bulletedArray.count) {
bulletedArray = [bulletedArray subarrayWithRange:NSMakeRange(1, len-1)];
}
//print out array
NSLog(@"%@",bulletedArray);
}
CRHCommentSection.h
#import <UIKit/UIKit.h>
@interface CRHCommentSection : UIViewController
@end
CRHCommentSection.m
#import "CRHCommentSection.h"
#import "CRHViewControllerScript.h"
@interface CRHCommentSection()
@end
@implementation CRHCommentSection
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *myArray = [CRHViewControllerScript theArray]; // This is how to call a Class Method in Objective C
NSLog(@"%@", myArray);
}
另外,我wouldnt假设在静态数据中传递数据是理想的,最好使用实例方法或属性,并获得对所需视图控制器实际实例的引用。 – 2012-08-08 19:28:59
@ user490696是的,作为一个规则,应该避免使用静态全局变量,但是我只是特别指出了问题的根源,这就是范围问题 – 2012-08-08 19:30:35
你能给我一个实例方法的例子吗?我是菜鸟。 – Craig 2012-08-08 19:31:40