Objective-C中的“description“方法

在Objective-C中,每个对象都继承自NSObject类,在NSObject类中定义了一个名为`description`的方法。该方法用于返回一个字符串,描述对象的内容。默认情况下,`description`方法返回的字符串是该对象的类名和其在内存中的地址。

下面是一个重写`description`方法的示例代码:

复制代码
@interface MyClass : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic) NSInteger age;

@end

@implementation MyClass

- (NSString *)description {
    return [NSString stringWithFormat:@"MyClass: Name=%@, Age=%ld", self.name, (long)self.age];
}

@end

定义了一个叫做`MyClass`的类,它包含了`name`和`age`两个属性

重写了`description`方法,使用`NSString`的`stringWithFormat:`方法

将`name`和`age`的值拼接到一个描述字符串中,并返回

复制代码
MyClass *myObject = [[MyClass alloc] init];
myObject.name = @"John";
myObject.age = 25;

NSLog(@"%@", myObject); // 输出: MyClass: Name=John, Age=25

通过重写`description`方法,你可以为自定义的类提供更有意义的描述信息,方便在日志输出和调试过程中使用。

需要注意的是,为了在控制台上输出一个对象的`description`内容,你可以使用`NSLog`方法,并将对象作为参数传递给`%@`占位符

相关推荐
如此风景5 分钟前
SwiftUI基础学习
ios
雪糕吖1 小时前
SwiftUI 自定义 Shape:实现顶部圆角矩形 RoundedTopRectangle
ios·swiftui
JarvanMo2 小时前
2025 年真正有效的 App Store 优化(ASO)
前端·ios
熊大与iOS13 小时前
iOS 长截图的完美实现方案 - 附Demo源码
android·算法·ios
songgeb21 小时前
DiffableDataSource in iOS
ios·swift
2501_916008891 天前
uni-app iOS 应用版本迭代与上架实践 持续更新的高效流程
android·ios·小程序·https·uni-app·iphone·webview
白玉cfc1 天前
【iOS】折叠cell
ios·objective-c
2501_915909061 天前
uni-app iOS 性能监控与调试全流程:多工具协作的实战案例
android·ios·小程序·https·uni-app·iphone·webview
他们都不看好你,偏偏你最不争气1 天前
【iOS】MVC架构
前端·ios·mvc·objective-c·面向对象