在Objective-C中定义一个类非常简单,它是面向对象编程的基础。首先需要了解`@interface`和`@implementation`这两个关键词。例如:
```objc
// 定义类的接口
@interface Person : NSObject
{
NSString name;
int age;
}
// 定义属性和方法
@property (nonatomic, copy) NSString name;
@property (nonatomic, assign) int age;
- (void)speak;
@end
// 实现类的功能
@implementation Person
@synthesize name, age;
- (void)speak {
NSLog(@"My name is %@, and I am %d years old.", self.name, self.age);
}
@end
```
以上的代码展示了如何创建一个名为`Person`的类,并为其添加了属性(`name`和`age`)以及方法(`speak`)。通过`@interface`声明类的结构,使用`@implementation`实现具体逻辑。
👨💻 在Xcode中编写Objective-C时,只需按照上述格式书写即可完成类的定义。同时,记得利用`@property`简化变量管理,结合`@synthesize`或自动合成特性提升开发效率。如果还有疑问,欢迎随时提问! 💡