copyWithZone error -[DataObject setECGCount:]: unrecognized selector sent to instance - objective-c

My application crashed with the following error:
-[Data Object set ECGCount:]: unrecognized selector sent to instance 0x281671ad0
I am trying to pass data between my main viewController class into DataObject class which will then finally pass this information into IntervalGraph class.
I am doing this using copyWithZone however am getting stuck.
here is the viewContoller.h Class:
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#interface ViewController : UIViewController<CPTPlotDataSource>
#property (nonatomic, assign) int eCGCount;
#property (nonatomic, assign) int eCGheartRate;
#end
and the relevant code in viewController.m
#property (nonatomic) DataObject *maxRecordedHR, *minRecordedHR, *currentData, *continuousData, *seizureData;
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter addObserver:self
selector:#selector(sensorDataUpdated)
name:#"LYRDeviceCommunicatorDataUpdated"
object:nil];
self.rollingAverageHRArray = [[NSMutableArray alloc]initWithCapacity:180];
self.currentData = [[DataObject alloc]init];
self.continuousData = [[DataObject alloc]init];
self.seizureData = [[DataObject alloc]init];
}
//fired by a 1 second timer
-(void)startIntervalGraph {
[self sensorDataUpdated];
if (self.currentData.heartrate == 0 )
{NSLog(#"No data");
} else {
self.rollingAverageLabel.text = [NSString stringWithFormat:#"rolling 3 min average %1.1f", self.currentData.rollingaverageheartrate];
[self.intervalGraph addDataObject:self.currentData]; // something wrong here
[self.intervalGraph updateGraph];
NSLog(#"Updating Interval Graph");
}
}
-(void) sensorDataUpdated {
//Heart Rate
self.currentData.heartrate = self.eCGheartRate;
NSLog(#"Current Data %d", self.currentData.heartrate);
}
-(void)setECGCount:(int)eCGCount
{
self.eCGheartRate = (int) eCGCount;
eCGCount = self.eCGCount;
NSLog(#"eCGCount %d", self.eCGCount);
}
then the DataObject.h class
#import <Foundation/Foundation.h>
#interface DataObject : NSObject <NSCopying>
#property int heartrate;
#property float rollingaverageheartrate;
#property float rrinterval;
#property NSTimeInterval occurrence;
#property NSInteger minHRsetting;
#property NSInteger maxHRsetting;
#property int alarmtripped;
#end
and the DataObject.m
#import "DataObject.h"
#import "CRPC_300SDK.h"
#import "ViewController.h"
#implementation DataObject
- (id)copyWithZone:(NSZone *)zone
{
id copy = class alloc] init];
if (copy) {
// Set primitives
[copy setECGCount:self.heartrate]; //THIS IS WHERE THE CRASH OCCURS.
//[copy setRrinterval:self.rrinterval];
[copy setRollingaverageheartrate:self.rollingaverageheartrate];
[copy setOccurrence:self.occurrence];
[copy setMinHRsetting:self.minHRsetting];
[copy setMaxHRsetting:self.maxHRsetting];
[copy setAlarmtripped:self.alarmtripped];
}
return copy;
}
When i call
[copy setECGCOUNT:self.heartrate];
The app crashes with the following error:
2020-08-20 11:58:57.884543+0100 PulseGuardian[3927:2317144]
-[DataObject setECGCount:]: unrecognized selector sent to instance 0x281671ad0
2020-08-20 11:58:57.885908+0100 PulseGuardian[3927:2317144] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[DataObject setECGCount:]:
unrecognized selector sent to instance 0x281671ad0'
How can i fix this problem?

As #Larme pointed out in the comments, i was referencing the wrong method in the
DataObject.m
The code read:
[copy setECGCount:self.heartrate];
when it should have read:
[copy setHeartrate:self.heartrate];
once code was changed the app worked as it should. Silly error on my behalf but will leave this here in case it helps anybody else in the future.

Related

App crashing while working with class and not going to catch

In my AppDelegate.m, I am doing something like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
#try {
// initalizing Meeting config
MeetingConfig *config = [[MeetingConfig alloc] init];
NSLog(#"Initalized Meeting Config: %#", config);
[config setRoomName:#"test123"];
NSLog(#"SetRoom name for Meeting config: %#", config.roomName);
NSString *clientId = #"";
NSLog(#"Unused Client id is: %#", clientId);
//Call UIView from here
}#catch (NSException *exception) {
NSLog(#"exception: %#", exception);
}
return YES;
}
Where my MeetingConfig.m file looks like this
#implementation MeetingConfig
- (id) init
{
if (self = [super init]) {
self.apiBase = #"https://api.in";
self.showSetupScreen = false;
self.autoTune = true;
}
return self;
}
- (void) setAuthToken:(NSString *)authToken
{
self.authToken = authToken;
}
- (void) setApiBase:(NSString *)apiBase
{
self.apiBase = apiBase;
}
// more code
and MeetingConfig looks like this
#import <Foundation/Foundation.h>
#interface MeetingConfig : NSObject
#property (nonatomic, assign) NSString* roomName;
#property (nonatomic, assign) NSString* authToken;
#property (nonatomic, assign)Boolean autoTune;
#property (nonatomic, assign)NSString* apiBase;
#property (nonatomic, assign)Boolean showSetupScreen;
- (void) setRoomName:(NSString *)roomName;
- (void) setAuthToken:(NSString *)authToken;
- (void) setShowSetupScreen:(Boolean)showSetupScreen;
- (void) setAutoTuneEnabled:(Boolean)autoTune;
- (id) init;
#end
Can someone help me in determining what I could be doing wrong here? and why doesn't it log exception in NSLog? Also, I am super new to objective C (i have been asked to stick with Objective c) and if anyone have any suggestion in regards to the code then please let me know.
Error
You're using assign for reference/pointer types: #property retain, assign, copy, nonatomic in Objective-C
They should probably be declared copy, because this is a kind of value object, I think.
No exceptions were caught because no exceptions were thrown. Throwing/catching exceptions for control flow is not common in Objective-C
You don't need to write explicit setter functions for #properties
You should prefer to use BOOL type instead of Boolean, with values of YES/NO instead of true/false.
You should return instancetype not id from init, at least in reasonably modern Objective C
Consider making an initialiser that takes all the properties (initWithRoomName:clientID:) and make them read only once set
You don't need to declare -(id) init in your header since it gets that from NSObject

How to properly use a protocol-defined property in Realm predicates?

I am trying to implement a cache system using Realm.
Depending on classes, the cache should have different lengths. I've therefore defined a StalenessChecking protocol:
#protocol StalenessChecking <NSObject>
#required
// nonatomic needed when using a getter
#property (readonly, nonatomic, getter=isStale) bool stale;
#optional
- (void) setStaleness: (NSTimeInterval) duration;
#end
and an object:
Interface file (DziObject.h)
#import "Realm.h"
#import "StalenessChecking.h"
#interface DziObject : RLMObject <StalenessChecking>
#property (readonly) NSDate* refresh;
#end
Implementation file (DiObject.m)
#import 'DziObject.h'
#implementation DziObject
{
NSTimeInterval stalenessInterval;
}
#synthesize stale = _stale;
- (instancetype)init
{
self = [super init];
if (self) {
_refresh = [NSDate date];
stalenessInterval = 120.0;
}
return self;
}
- (bool) isStale {
return [[NSDate dateWithTimeInterval:stalenessInterval sinceDate:_refresh] timeIntervalSinceReferenceDate]< [[NSDate date] timeIntervalSinceReferenceDate];
}
- (void)setStaleness:(NSTimeInterval) duration
{
stalenessInterval = duration;
}
#end
I then call them from a Facade:
Interface:
#import <Foundation/Foundation.h>
#interface SDK_Facade : NSObject
+ (void) createDziO;
#end
Implementation:
#import "SDK_Facade.h"
#import "DziObject.h"
#implementation SDK_Facade
+ (void) createDziO
{
DziObject *dziO = [[DziObject alloc] init];
// both work fine
if (dziO.isStale) {
NSLog(#"Is stale");
}
if (dziO.stale) {
NSLog(#"Is really stale");
}
// Query Realm for all results less than 2 minutes old
// TODO: -- currently crashes
RLMResults< DziObject *> * dzios = [DziObject objectsWhere:#"stale == %#", #YES];
NSLog(#"DziOs: %lu", (unsigned long)dzios.count);
// Persist your data easily
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
[realm addObject:dziO];
}];
// Queries should update in realtime
NSLog(#"DO: %lu", (unsigned long)dzios.count);
}
#end
I get an ugly crash:
Terminating app due to uncaught exception 'Invalid property name', reason: 'Property 'stale' not found in object of type 'DziObject'
You can't define a Realm model property in a protocol that the model class conforms to. It must be done in the class definition itself.
#interface DziObject : RLMObject <StalenessChecking>
#property NSDate* refresh;
#property (getter=isStale) bool stale;
#end

Setting delegate - unrecognized selector sent to instance

i have some problems with delegates under xcode while programming an application for Mac OS. I want to communicate with mobile phones if they are in the same network via TCP. I have the following server integrated in my project:
https://github.com/tuscland/osc-echo-example/blob/master/TCPServer.m
https://github.com/tuscland/osc-echo-example/blob/master/TCPServer.h
The only thing I changed at the server is that I extended the start-method so that I can specify a special port. Also I changed the TCPServerDelegation in TCPServer.h to #protocol.
Now I want to set the delegate to this class. But then I get the following error:
[MobileSync copyWithZone:]: unrecognized selector sent to instance 0x109e0f950
I tried a lot but I could not found any solution.
Here is my code, some irrelevant functions are taken out:
MobileSync.h
#import <Foundation/Foundation.h>
#import "TCPServer.h"
#interface MobileSync: NSObject <TCPServerDelegation> {
}
-(id)init;
-(void)StartServer:(int)port;
-(void)StopServer;
// Properties
#end
MobileSync.m
#import "MobileSync.h"
#import "TCPServer.h"
#implementation MobileSync {
TCPServer *tcpServer;
// Other variables
}
-(id)init {
self = [super init];
if (self != nil) {
// Fill variables with values
}
return self;
}
-(void)StartServer:(int)port {
tcpServer = [[TCPServer alloc] init];
[tcpServer setDelegate:self] // <<<<<<< This line is broken
NSError *__autoreleasing* error = NULL;
if ([tcpServer start:port error:error]) {
NSLog(#"Server started successfully");
}
}
-(void)StopServer {
if (tcpServer.stop)
NSLog(#"Server stoped successfully");
}
// different sync functions
// tcpServer Delegate function
-(void)TCPServer:(TCPServer *)server didReceiveConnectionFromAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr {
NSLog(#"Connection received.");
}
TCPServer.h
#import <Foundation/Foundation.h>
#import <CoreServices/CoreServices.h>
NSString * const TCPServerErrorDomain;
typedef enum {
kTCPServerCouldNotBindToIPv4Address = 1,
kTCPServerCouldNotBindToIPv6Address = 2,
kTCPServerNoSocketsAvailable = 3,
} TCPServerErrorCode;
#interface TCPServer : NSObject {
#private
id delegate;
NSString *domain;
NSString *name;
NSString *type;
uint16_t port;
CFSocketRef ipv4socket;
CFsocketRef ipv6socket;
NSNetService *netService;
}
#property (readwrite, copy) id delegate;
#property (readwrite, copy) NSString *domain;
#property (readwrite, copy) NSString *name;
#property (readwrite, copy) NSString *type;
#property (readwrite) uint16_t port;
-(BOOL)start:(int)port error:(NSError **)error;
-(BOOL)stop;
-(void)handleNewConnectionFromAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr;
#end
#protocol TCPServerDelegation
-(void)TCPServer:(TCPServer *)server didReceiveConnectionFromAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr;
#end
Can someone help me solving the problem? That would be great

Unrecognized selector sent to instance

Actually, the problem is in
#property (nonatomic, copy) NSMutableArray* arrayOfObjects;
should be:
#property (nonatomic, strong) NSMutableArray* arrayOfObjects;
yeah? Thank,s for that guys!
I do not exactly understand how this bug worked, but I will try to get to know :)
I have trying to solve one problem since over an hour... I am afraid it is something very simple, but something I do not understand yet. I am guessing that this is something with memory management stuff cause this is my definitely weak point yet.
Post a little bit similar to
'Unrecognized selector sent to instance'
and some others but they didnt solved my problem...
In a nutshell (pasting much cause don't know where the potential bug is):
#interface MyCustomObject : NSObject {
NSString* name;
int birthDate;
double heightInMeters;
}
#property(strong, nonatomic) NSString * name;
#property(nonatomic) int birthDay;
#property(nonatomic) double heightInMeters;
-(id)initWithDate:(int)birthDate
AndName:(NSString *)nameString
AndHeight:(double)h;
#end
//////////////////////////////////
#import "MyCustomObject.h"
#implementation MyCustomObject
#synthesize name;
#synthesize birthDay;
#synthesize heightInMeters;
-(id)initWithDate:(int)bd AndName:(NSString *)nameString AndHeight:(double)h{
if(self = [super init]){
self.birthDay = bd;
self.name = nameString;
self.heightInMeters = h;
return self;
}
return nil;
}
#end
And some kind of database for MyCustomObjects:
DataCollection.h:
#interface DataCollection : NSObject{
NSMutableArray* arrayOfObjects;
}
#property (nonatomic, copy) NSMutableArray* arrayOfObjects;
-(void)addElement:(id)el;
#end
And implementation:
#import "DataCollection.h"
#implementation DataCollection
#synthesize arrayOfObjects;
-(id)init{
if(self = [super init]){
self.arrayOfObjects = [[NSMutableArray array] init];
NSLog(#"Number of record before init: %d", [self.arrayOfObjects count]);
[self addElement:[[MyCustomObject alloc] initWithDate:1988 AndName:#"Georg" AndHeight:1.88]];
[self addElement:[[MyCustomObject alloc] initWithDate:1951 AndName:#"Sebastian" AndHeight:1.58]];
NSLog(#"Number of record before init: %d", [self.arrayOfObjects count]);
return self;
}
return nil;
}
-(void)addElement:(id)el{
// UNRECOGNIZED SELECTOR ????
[self.arrayOfObjects addObject:el];
}
#end
Result is:
2013-03-05 15:42:56.826 XMLTest[11787:207] Number of record before
init: 0 Current language: auto; currently objective-c 2013-03-05
15:43:51.446 XMLTest[11787:207] -[__NSArrayI addObject:]: unrecognized
selector sent to instance 0x6816110
Do you see what I am doing wrong? I am guessing that this is something with memory management stuff
If you change
#property (nonatomic, copy) NSMutableArray* arrayOfObjects;
to
#property (nonatomic, strong) NSMutableArray* arrayOfObjects;
That should fix your problem
I didn't actually read your question - it's too long, but I think I may know your problem. Looking only at the debugger output at the end of your post, it looks like you're trying to send addObject: to an NSArray object. If you want to add and remove objects to an array, you need to use NSMutableArray instead.

Getting error NSInternalInconsistencyException "Argument must be non-nil"

I run this code:
- (void)unitButtonButtonTapped:(id)sender {
[_label setString:#"Last button: Unembossed square"];
MilitaryUnits *target = nil;
target = [Peasants militaryUnits];
target.position = ccp(100, 450);
[self addChild:target];
}
And I get this error:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Argument must be non-nil'
These are my .h and .m class files
#import "cocos2d.h"
#interface MilitaryUnits : CCSprite {
int _experience;
int _number_of_units;
int _stamina;
int _armor_level;
int _weapon_levell;
}
#property (nonatomic, assign) int experience;
#property (nonatomic, assign) int number_of_units;
#property (nonatomic, assign) int stamina;
#property (nonatomic, assign) int armor_level;
#property (nonatomic, assign) int weapon_levell;
#end
#interface Peasants : MilitaryUnits{
}
+(id)militaryUnits;
#end
#import "MilitaryUnits.h"
#implementation MilitaryUnits
#synthesize number_of_units = _number_of_units;
#synthesize stamina = _stamina;
#synthesize experience = _experience;
#synthesize armor_level = _armor_level;
#synthesize weapon_levell = _weapon_levell;
#end
#implementation Peasants
+ (id)militaryUnits {
Peasants *militaryUnits = nil;
if ((militaryUnits = [[[super alloc] initWithFile:#"Target.png"] autorelease])) {
}
return militaryUnits;
}
#end
Note, I'm using cocos 2d
looks to me like your sprite is nil, ie the file "Target.png" is not found. Make certain the file name has the same case (in finder) as you spelled out in your code, and that the file is included in the target's membership in Xcode.
Also
+ (id)militaryUnits {
Peasants *militaryUnits;
if ((militaryUnits = [[[super alloc] initWithFile:#"Target.png"] autorelease])) {
return militaryUnis;
} else {
CCLOGERROR(#"your favorite whine style for errors like file not found");
return nil;
}
}