关于objective-c类方法与实例方法的一些疑问
巴扎黑
巴扎黑 2017-04-24 09:13:06
0
2
463

之前都是在搞前端js
之后写ios开始慢慢接触objective-c
有个疑问

//实例方法调用
NSString *str1 = [[NSString alloc] initWithString:@"123123"];

//类方法调用
NSString *str2 = [NSString stringWithString@"123123"];

我的疑问可能用上面例子会不太能凸显出来
疑问在于,
实例方法必须创建一个实例后使用实例进行调用
也就是内存中必存在一个实例
如果我想不通过实例来达到某些操作
那在设计API时可以设计成类方法,这样就可以直接通过类名进行调用
但是这种情况难道就不会生成实例在内存中了吗??
或者说,虽然没有生成实例,但内存依然会分配空间
那如果

[XXXClass abc];
[XXXClass bcd];
[XXXClass cde];
[XXXClass def];

这种情况下,内存会分配多少块内存空间呢?
而但代码域(如方法内)结束后,内存空间又是否能正常释放呢?

巴扎黑
巴扎黑

reply all(2)
阿神

In the example you gave, whether it is an object method or a class method, their purpose is to obtain an object instance.
How can you configure your objects without allocating memory space first?
Maybe the class method is implemented like this:

+ (instancetype)stringWithString:(NSString *)string {
    NSString *str = [[self alloc]initWithString:string];
    return str;
}
PHPzhong

Hold down ctrl and click NSString to take a look.

- (instancetype)initWithString:(NSString *)aString;
+ (instancetype)stringWithString:(NSString *)string;

Look at the front of these two methods, one is "-" and the other is "+"
In oc, if you declare a method with a plus sign, you can call the method of this class without instantiation.
If you declare a method with a minus sign, you need to alloc an object first before you can call the method in this class.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template