-1

新手到目标C...

注意:这是一个概念问题,因为我试图从我对其他语言的了解中翻译“公共和私人”。

如何通过“public”方法访问“stringB”ivar?

我的类.h

@interface myClass : UIViewController {

}

@property (nonatomic, retain) NSString *stringA;
@property (nonatomic, retain) NSString *stringB;

- (void)dealWithStringA;
+ (void)dealWithStringB;

我的班级.m

#import "myClass.h"

@interface myClass () {

}
@end

@implementation myClass

// My "private" function
- (void)dealWithStringA
{
    return _stringA;
}

// My "public" function
+ (void)dealWithStringB
{
    // Errors with: Instance variable "stringB" accessed in class method
    return _stringB;
}
4

4 回答 4

2

以a开头的+方法在Objective C中称为类方法,其中以a开头的方法-是实例方法。实例方法只能在该类的实例上执行。

此外,您的方法的返回类型将是 an,NSString因为您希望从该方法中获取一个字符串对象。

对于类方法,您需要创建该类的自动释放实例,然后对该实例执行操作。

例如。

+ (NSString*)dealWithStringB
{
    MyClass *myClass = [[[MyClass alloc] init] autorelease];
    myClass.stringB = @"Its String B";//It's an absurd example 
    return myClass.stringB;
}
于 2013-10-17T08:49:58.367 回答
1

“+”前缀表示类方法,不是公共的。“-”代表实例方法,不是私有的。

公共和私有方法都可以访问类或实例的私有状态。

于 2013-10-17T08:49:43.953 回答
1

您对“+”、“-”的理解是错误的——这与私有/公共无关。

要拥有一个私有函数,你应该在你的 .m 文件中实现它:

@interface YourClass ()
- (id) privateMethod;
@end

您在 .h 文件中声明的所有内容都将是公开的:

@interface YourClass : NSObject
- (id)someMethod //public
@end

“+”用于静态函数,因此您可以在没有类实例的情况下调用它们。例如在你的情况下:

[myClass dealWithStringB];

对于“-”功能,您需要实例。

[[[myClass alloc] init] dealWithStringA];

当您不需要类中的任何属性或者它们经常用于创建类的实例时,可以使用静态函数。

于 2013-10-17T08:51:42.323 回答
0

myClass.h (类似于你的)

@interface myClass : UIViewController
   {

   }

@property (nonatomic, retain) NSString *stringA;
@property (nonatomic, retain) NSString *stringB;

- (void)dealWithStringA;
+ (void)dealWithStringB;

 @end

我的班级.m

 @implementation myClass
 @synthesize stringA ;
 @synthesize stringB ;

 static myClass* instance = nil;
 +(void) dealWithStringB
   {
       if(instance==nil)
        {
           instance=[myClass alloc]init];
        }

        else
         {
            //Access the field this way
                  printf("@"The string content is %@",instance.stringB);
         } 

   }

希望清楚!!!

于 2013-10-17T09:09:06.860 回答