我知道HIG(这非常方便!),但是在编写Objective-C时,更具体地说,在使用Cocoa(或CocoaTouch)时,您使用了什么编程实践?
当前回答
#import "MyClass.h"
@interface MyClass ()
- (void) someMethod;
- (void) someOtherMethod;
@end
@implementation MyClass
其他回答
简单但经常被遗忘。根据规格:
一般来说,方法各不相同 具有相同选择器的类 (相同的名字)也必须共享 相同的返回值和参数类型。这 约束是由编译器施加的 允许动态绑定。
在这种情况下,所有相同的命名选择器,即使在不同的类中,也会被认为具有相同的返回/参数类型。这里有一个简单的例子。
@interface FooInt:NSObject{}
-(int) print;
@end
@implementation FooInt
-(int) print{
return 5;
}
@end
@interface FooFloat:NSObject{}
-(float) print;
@end
@implementation FooFloat
-(float) print{
return 3.3;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id f1=[[FooFloat alloc]init];
//prints 0, runtime considers [f1 print] to return int, as f1's type is "id" and FooInt precedes FooBar
NSLog(@"%f",[f1 print]);
FooFloat* f2=[[FooFloat alloc]init];
//prints 3.3 expectedly as the static type is FooFloat
NSLog(@"%f",[f2 print]);
[f1 release];
[f2 release]
[pool drain];
return 0;
}
确保您收藏了调试魔术页面。这应该是你在寻找Cocoa bug的源头时碰壁的第一站。
例如,它会告诉你如何找到你第一次分配内存的方法,后来导致崩溃(比如在应用程序终止期间)。
黄金法则:如果你分配了,那么你就释放了!
更新:除非你正在使用ARC
使用标准的Cocoa命名和格式化约定和术语,而不是使用其他环境中使用的任何术语。有很多Cocoa开发人员,当他们中的另一个人开始使用您的代码时,如果它看起来和感觉上与其他Cocoa代码相似,那么它将更容易接近。
做什么和不做什么的例子:
Don't declare id m_something; in an object's interface and call it a member variable or field; use something or _something for its name and call it an instance variable. Don't name a getter -getSomething; the proper Cocoa name is just -something. Don't name a setter -something:; it should be -setSomething: The method name is interspersed with the arguments and includes colons; it's -[NSObject performSelector:withObject:], not NSObject::performSelector. Use inter-caps (CamelCase) in method names, parameters, variables, class names, etc. rather than underbars (underscores). Class names start with an upper-case letter, variable and method names with lower-case.
无论你做什么,不要使用Win16/ win32风格的匈牙利符号。甚至微软也在转向。net平台时放弃了这一点。
编写单元测试。您可以在Cocoa中测试许多在其他框架中可能比较困难的事情。例如,对于UI代码,您通常可以验证事物是否按照应有的方式连接,并相信它们在使用时能够正常工作。你可以很容易地设置状态和调用委托方法来测试它们。
在编写内部测试时,也不会有公共、受保护和私有方法可见性。
推荐文章
- 在成功提交我的应用程序后,“太多符号文件”
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 如何从UIImage (Cocoa Touch)或CGImage (Core Graphics)获取像素数据?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- 为什么单元测试中的代码不能找到包资源?
- CFNetwork SSLHandshake iOS 9失败
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- Xcode构建失败“架构x86_64未定义的符号”