nil / Nil / NULL / NSNull

本文探讨了Objective-C中代表无或空的不同方式,包括NULL、nil、Nil和NSNull的区别及用法,并提供了如何正确比较NSNull的建议。

Understanding the concept of nothingness is as much a philosophical issue as it is a pragmatic one. We are inhabitants of a universe of somethings, yet reason in a logical universe of existential uncertainties. As a physical manifestation of a logical system, computers are faced with the intractable problem of how to represent nothing with something.

In Objective-C, there are several different varieties of nothing. The reason for this goes back to a common NSHipster refrain, of how Objective-C bridges the procedural paradigm of C with Smalltalk-inspired object-oriented paradigm.

C represents nothing as 0 for primitive values, and NULL for pointers (which is equivalent to 0 in a pointer context).

Objective-C builds on C's representation of nothing by adding nilnil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.

On the framework level, Foundation defines NSNull, which defines a class method, +null, which returns the singleton NSNull object. NSNull is different from nil or NULL, in that it is an actual object, rather than a zero value.

Additionally, in Foundation/NSObjCRuntime.hNil is defined as a class pointer to nothing. This lesser-known title-case cousin of nil doesn't show up much very often, but it's at least worth noting.

There's Something About nil

Newly-alloc'd NSObjects start life with their contents set to 0. This means that all pointers that object has to other objects begin as nil, so it's unnecessary to, for instance, set self.(association) = nil in init methods.

Perhaps the most notable behavior of nil, though, is that it can have messages sent to it.

In other languages, like C++, this would crash your program, but in Objective-C, invoking a method on nil returns a zero value. This greatly simplifies expressions, as it obviates the need to check fornil before doing anything:

// For example, this expression...if (name != nil && [name isEqualToString:@"Steve"]) { ... }

// ...can be simplified to:
if ([name isEqualToString:@"steve"]) { ... }

Being aware of how nil works in Objective-C allows this convenience to be a feature, and not a lurking bug in your application. Make sure to guard against cases where nil values are unwanted, either by checking and returning early to fail silently, or adding a NSParameterAssert to throw an exception.

NSNull: Something for Nothing

NSNull is used throughout Foundation and other frameworks to skirt around the limitations of collections like NSArray and NSDictionary not being able to contain nil values. You can think of NSNull as effectively boxing the NULL or nil value so that it can be used in collections:

NSMutableDictionary*mutableDictionary = [NSMutableDictionary dictionary];
mutableDictionary[@"someKey"] = [NSNull null]; // Sets value of NSNull singleton for `someKey`
NSLog(@"Keys: %@", [mutableDictionary allKeys]); // @[@"someKey"]

So to recap, here are the four values representing nothing that every Objective-C programmer should know about:

Symbol Value Meaning
NULL(void *)0literal null value for C pointers
nil(id)0literal null value for Objective-C objects
Nil(Class)0literal null value for Objective-C classes
NSNull[NSNull null]singleton object used to represent null

Comparing to NSNull

JAN 6TH, 2012

Checks to NSNull come up a lot when dealing with things like parsing JSON and while it’s mostly just ==, there are some options.

The officially sanctioned method is NSNull sample code, but this will generate a warning in clang (BOOO HISSSS).

So here are the options as I see them:

- (void)someMethod
{
    NSString *aString = @"loremipsum";
    
    // This will complain: "Comparison of distinct pointer types ('NSString *' and 'NSNull *')"
    if (aString != [NSNull null])
    {
        
    }
    
    // This works (at least for strings), but isEqual: does different things 
    // for different classes, so it's not ideal
    if ([aString isEqual:[NSNull null]]) 
    {
        
    }
    
    // If you cast it to the class you're comparing against
    // then you're good to go
    if (aString != (NSString *)[NSNull null])
    {
        
    }
    
    // But we can also just cast it to id and
    // that works generically
    if (aString != (id)[NSNull null])
    {
        
    }
    
    // The thing that would be really cool,
    // would be [NSNull null] returning
    // id (like in the sample category below).
    // Wouldn't count on that one though.
    if (aString != [NSNull idNull])
    {
        
    }
}
@interface NSNull (idNull)
+ (id)idNull;
@end
@implementation NSNull (idNull)
+ (id)idNull { return [NSNull null]; }
@end

Casting to (id) seems like the simplest way to handle this one, so that’s the one I’m using right now.

Update:

One of my coworkers, @pgor, pointed out that he uses NSNull’s isEqual, which seems like a sensible enough thing to do. (I’m guessing Apple isn’t going to toss anything to screwy into an isEqual on an object that’s basically single purpose.)

if ([[NSNull null] isEqual:aString]) 
{
        
}

Also forgot to mention in the original post: it’s worth filing a bug against the documentation on NSNull to see what Apple’s official position is in this post static humiliator world we inhabit.


Ref:

1. nil / Nil / NULL / NSNull
2. Comparing to NSNull

【负荷预测】基于VMD-CNN-LSTM的负荷预测研究(Python代码实现)内容概要:本文介绍了基于变分模态分解(VMD)、卷积神经网络(CNN)和长短期记忆网络(LSTM)相结合的VMD-CNN-LSTM模型在负荷预测中的研究与应用,采用Python代码实现。该方法首先利用VMD对原始负荷数据进行分解,降低序列复杂性并提取不同频率的模态分量;随后通过CNN提取各模态的局部特征;最后由LSTM捕捉时间序列的长期依赖关系,实现高精度的负荷预测。该模型有效提升了预测精度,尤其适用于非平稳、非线性的电力负荷数据,具有较强的鲁棒性和泛化能力。; 适合人群:具备一定Python编程基础和深度学习背景,从事电力系统、能源管理或时间序列预测相关研究的科研人员及工程技术人员,尤其适合研究生、高校教师及电力行业从业者。; 使用场景及目标:①应用于日前、日内及实时负荷预测场景,支持智慧电网调度与能源优化管理;②为研究复合型深度学习模型在非线性时间序列预测中的设计与实现提供参考;③可用于学术复现、课题研究或实际项目开发中提升预测性能。; 阅读建议:建议读者结合提供的Python代码,深入理解VMD信号分解机制、CNN特征提取原理及LSTM时序建模过程,通过实验调试参数(如VMD的分解层数K、惩罚因子α等)优化模型性能,并可进一步拓展至风电、光伏等其他能源预测领域。
【轴承故障诊断】基于融合鱼鹰和柯西变异的麻雀优化算法OCSSA-VMD-CNN-BILSTM轴承诊断研究【西储大学数据】(Matlab代码实现)内容概要:本文研究了一种基于融合鱼鹰和柯西变异的麻雀优化算法(OCSSA)优化变分模态分解(VMD)参数,并结合卷积神经网络(CNN)与双向长短期记忆网络(BiLSTM)的轴承故障诊断模型。该方法利用西储大学轴承数据集进行验证,通过OCSSA算法优化VMD的分解层数K和惩罚因子α,有效提升信号去噪与特征提取能力;随后利用CNN提取故障特征的空间信息,BiLSTM捕捉时间序列的长期依赖关系,最终实现高精度的轴承故障识别。整个流程充分结合了智能优化、信号处理与深度学习技术,显著提升了复杂工况下故障诊断的准确性与鲁棒性。; 适合人群:具备一定信号处理、机器学习及MATLAB编程基础的研究生、科研人员及从事工业设备故障诊断的工程技术人员。; 使用场景及目标:①解决传统VMD参数依赖人工经验选择的问题,实现自适应优化;②构建高效准确的轴承故障诊断模型,适用于旋转机械设备的智能运维与状态监测;③为类似机电系统故障诊断提供可借鉴的技术路线与代码实现参考。; 阅读建议:建议结合提供的Matlab代码进行实践操作,重点关注OCSSA算法的设计机制、VMD参数优化过程以及CNN-BiLSTM网络结构的搭建与训练细节,同时可尝试在其他故障数据集上迁移应用以加深理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值