我是objective c和xcode的新手,所以请原谅我在使用正确的技术术语时的错误。
我创建了一个新项目,并创建了一个应用程序委托(.h和.m文件)。在应用委托中,我有一些变量(设置)。其中一个变量是mainImage。我把它放在appdelegate中,因为我希望它可以从任何视图控制器访问。
我添加了一个名为MainViewController (.h和.m文件)的视图控制器。在我的MainViewController (.m)中,我有一些自定义方法。在viewDidLoad方法中,我有以下代码
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
[currentImage setImage:appDelegate.mainImage];问题:
在MainViewController的任何方法中,每当我想要读取"mainImage“时,我都必须执行上述两行操作。
在.m文件中有没有一个地方,你可以只做一次,并且它在该文件的所有方法中都可用?
先谢谢你,普拉萨德。
发布于 2012-09-28 03:27:16
@Malloc和@jack...that非常接近我的needed..nevertheless,我有相当多的properties..hence我结束了,包括在头文件中的调用……
#define appDelegate ((MyAppDelegate *)[UIApplication sharedApplication].delegate)然后我调用appDelegate.any_of_my_properties
从我的C#经验来看,我知道在应用委托中包含一个全局变量并在这个way..however中引用它可能是一种糟糕的做法..我认为这使得sense..given对象实际上并没有绑定到任何特定的视图控制器(图像只是一个例子)..我有一些动态值持有者。
发布于 2012-09-28 02:32:59
你可以用MainViewController中的这两行代码编写一个方法,返回一个UIImage类型的对象或其他类型的对象,然后直接调用它。调用应该类似于[self mainImage],方法签名应该是- (UIImage *)mainImage。
发布于 2012-09-28 03:12:09
您可以将这两行放入MainViewController的viewDidLoad方法中,如下所示:
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
[currentImage setImage:appDelegate.mainImage];这样做一次,然后每次需要currentImage内容时,您只需调用它:
UIImage *img= [[UIImage alloc]init];
img = self.currentImage;假设在MainViewController中将currentImage声明为property。
https://stackoverflow.com/questions/12627692
复制相似问题