Objective-C Primer(2)Private Methods and Class Properties
- Author: 柳大·Poechant(钟超)
- Email: zhongchao.ustc#gmail.com (# -> @)
- Blog: Blog.youkuaiyun.com/Poechant
- Date: May 6th, 2012
1 What the relationship between C and Objective-C?
If you want, you can just program in C language style and syntax, and there will be no error or warning if you never make mistakes of C programming. Therefore, you must say: Getcha!
Yes! Objective-C is a super set of C language, just like C++ to C.
2 No private methods declaration in .h file?
Yes, you are right. But think it twice. Is it more reasonable to hide or ignore private methods declaration in header file? Every invoker just appears in member methods of .m source code files, so it’s unnecessary to give any clue for private methods in header file.
Do you know how to hide private methods declaration in C++? (Give you a hint: pimpl idiom.)
Now I will show how to do that. The .h is still the one I introduce in Objective-C Primer (1) Get started! But how about .m file?
//
// TestClass.m
// ObjectiveCTest
//
// Created by 超 钟 on 12-5-6.
// Copyright (c) 2012年 http://blog.youkuaiyun.com/poechant. All rights reserved.
//
#import "TestClass.h"
@implementation TestClass
@synthesize foo;
-(void)privateMethod
{
NSLog(@"I'm a priavte method, named 1");
}
-(void)someMethod
{
NSLog(@"some method got called");
[self privateMethod];
}
But notice that there will be a warning if you invoke a private method below the invoker method. Just like the following.

3 Class properties
As we know at present, in Objective-C, a class consists of an interface which is visible for external users and an implementation for class behavior details.
What about properties?
There are some many identifiers for properties, which will be messed up.
retainwill increase the reference counter, and of course set the value of the pointer.assigndoes not increate the reference counter, but also set the value of the pointer.copywill create a new object, which is the same as the source object. But this new object has its own new reference counter.
You should notice that any two of these three identifier could not be used together.
nonatomicmeans this object is not thread safe. So you must guess it. Yes! If you do not usenonatomicand just use the default, the object will be thread safe and there will be scoped lock used internally.
-
转载请注明来自柳大的优快云博客:Blog.youkuaiyun.com/Poechant
-
本文深入探讨了Objective-C中私有方法的隐藏与使用,以及类属性(properties)的多种实现方式,包括retain、assign、copy等,并解释了nonatomic标识符的含义及其对线程安全的影响。

被折叠的 条评论
为什么被折叠?



