I have an object that I use like this
[PeripheralManager readValueForCharacteristic:[CBUUID UUIDWithString:CHARACTERISTIC_TX_POWER_LEVEL]
inService:[CBUUID UUIDWithString:SERVICE_TX_POWER]
completionBlock:^(NSData *value) {
//code
}];
The problem is that if I doesn't save the object in a strong property when I call completionBlock the app crashes.
You can say "Save your PeripheralManager in a strong property"... well there are some situation in witch I have to read a value and than another value again e so on, maybe for 3 or 4 times.
In other situation is possible call class method that returns some values in a block and the block is not deallocated. Is there a way to keep mi PeripheralManager in memory ?
Edit
+ (id)readValueForCharacteristic:(CBUUID *)cUUID
inService:(CBUUID *)sUUID
completionBlock:(completionBlock)completionBlock
{
return [[self alloc] initForReadValueForCharacteristic:cUUID
inService:sUUID
completionBlock:completionBlock];
}
- (id)initForWriteValue:(unsigned char)value
forCharacteristic:(CBUUID *)cUUID
inService:(CBUUID *)sUUID
completionBlock:(completionBlock)completionBlock
{
self = [super init];
if (self)
{
self.completionBlock = [completionBlock copy];
self.accessType = PeripheralAccessTypeWrite;
self.valueToSet = value;
if (cUUID && sUUID)
{
self.sUUID = sUUID;
self.cUUID = cUUID;
self.connectedPeripheral = [[BLEManager manager] getConnectedPeripheral];
self.connectedPeripheral.delegate = self;
if (self.connectedPeripheral && self.connectedPeripheral.state == CBPeripheralStateConnected)
{
[self.connectedPeripheral discoverServices:#[sUUID]];
}
}
else NSLog(#"cUUID and sUUID are mandatory");
}
return self;
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
// NSLog(#"didDiscoverServices");
for (CBService *service in peripheral.services)
{
if ([service.UUID isEqual:self.sUUID])
{
[peripheral discoverCharacteristics:#[self.cUUID] forService:service];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (service.UUID.UUIDString.length >= 8)
{
for (CBCharacteristic *characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:self.cUUID])
{
if (self.accessType == PeripheralAccessTypeRead)
{
self.connectedCharacteristic = characteristic;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
[peripheral readValueForCharacteristic:characteristic];
}
else
{
self.connectedCharacteristic = characteristic;
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
unsigned char dat = self.valueToSet;
NSLog(#"dat %i", dat);
NSData * valueData = [NSData dataWithBytes:&dat length:1];
NSLog(#"valueData %#",valueData);
[peripheral writeValue:valueData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
}
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error)
{
NSLog(#"%#",error.localizedDescription);
}
else
{
NSString * characteristicName = [self getCharacteristicName:characteristic];
NSData * value = [self readValueFromCharacteristic:characteristic];
NSLog(#"update %#: %#",characteristicName ,value);
self.completionBlock(value);
}
}
Thanks
Related
I am trying to acquire token Interactively for multiple scopes, Policy and RMS scopes using Objective C. I am not sure whether I am doing it right or wrong, the way I am trying to get it as below.
I have written a method "aquireToken" where I am calling the function twice one for Policy scope and other RMS scope and updating result in NSDictionary.
There is a flag which is being updated inside the "completionBlock = ^(MSALResult *result, NSError *error)". But its value is not reflected in the caller "aquireToken" function.
The code snippet is as below:
- (void) aquireToken
{
policyTokenResult = false;
rmsTokenResult = false;
NSError *error = nil;
MSALPublicClientApplication *application = [self createPublicClientApplication:&error];
[self retrieveTokens:application forScopes:scopesPolicy isPolicy:true];
if (policyTokenResult)
{
[self retrieveTokens:application forScopes:scopesRMS isPolicy:false];
}
for (NSString* key in resultMap) {
id value = resultMap[key];
// id object = [resultDict objectForKey:key];
NSLog(#"%# = %#", key, value);
// do stuff
}
}
- (void)retrieveTokens:(MSALPublicClientApplication*) application
forScopes: (NSArray<NSString *> *) scopes
isPolicy: (BOOL) isPolicy
{
NSError *error = nil;
MSALAccount* userAccount = nil;
for (MSALAccount *account in [application allAccounts:&error])
{
if([[account.username uppercaseString] isEqualToString:[authID uppercaseString]])
{
NSLog(#"Account Found: \t%#", account.username);
userAccount = account;
break;
}
}
MSALCompletionBlock completionBlock;
__block __weak MSALCompletionBlock weakCompletionBlock;
weakCompletionBlock = completionBlock = ^(MSALResult *result, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^{
if (!error)
{
if (isPolicy)
{
[resultMap setObject:result.accessToken forKey:#"PolicyAccessToken"];
[resultMap setObject:result.account.username forKey:#"UserId"];
authID = result.account.username;
policyTokenResult = true;
}
else
{
[resultMap setObject:result.accessToken forKey:#"RMSAccessToken"];
rmsTokenResult = true;
}
if(policyTokenResult && rmsTokenResult)
{
[resultMap setObject:#"" forKey:#"ResultStatusSuccess"];
}
return;
}
if ([error.domain isEqualToString:MSALErrorDomain] && error.code == MSALErrorInteractionRequired)
{
[self acquireTokenInteractive:application scopes:scopes isPolicy:isPolicy completionBlock:weakCompletionBlock];
return;
}
});
};
if(userAccount)
{
[self acquireTokenSilent:application scopes:scopes forAccount:userAccount isPolicy:isPolicy completionBlock:completionBlock];
}
else
{
[self acquireTokenInteractive:application scopes:scopes isPolicy:isPolicy completionBlock:completionBlock];
}
}
- (void) acquireTokenSilent: (MSALPublicClientApplication *) application
scopes: (NSArray<NSString *> *) scopes
forAccount: (MSALAccount *) userAccount
isPolicy: (BOOL) isPolicy
completionBlock: (MSALCompletionBlock) completionBlock
{
MSALSilentTokenParameters *silentParams = [[MSALSilentTokenParameters alloc] initWithScopes:scopes account:userAccount];
[application acquireTokenSilentWithParameters:silentParams completionBlock:completionBlock];
}
- (void) acquireTokenInteractive: (MSALPublicClientApplication *) application
scopes: (NSArray<NSString *> *) scopes
isPolicy: (BOOL) isPolicy
completionBlock: (MSALCompletionBlock)completionBlock
{
MSALInteractiveTokenParameters *interactiveParams = [[MSALInteractiveTokenParameters alloc] initWithScopes:scopes];
[interactiveParams setPromptType:MSALPromptTypeSelectAccount];
interactiveParams.completionBlockQueue = dispatch_get_main_queue();
[application acquireTokenWithParameters:interactiveParams completionBlock:completionBlock];
}
I have 3 dependent signals and I want to combine their values into a single object. I came up with 2 options.
Option 1:
+ (RACSignal *)createObject {
RACSignal *paramsSignal = [[[self class] createObject1] flattenMap:^RACStream *(NSString *object1) {
return [[[self class] createObject2:object1] flattenMap:^RACStream *(NSString *object2) {
return [[[self class] createObject3:object2] flattenMap:^RACStream *(NSString *object3) {
return [RACSignal return:RACTuplePack(object1, object2, object3)];
}];
}];
}];
return [paramsSignal map:^id(RACTuple *tuple) {
return [[CombinedObject alloc] initWithO1: tuple.first O2: tuple.second O3: tuple.third];
}];
}
I don't quite like all that nesting and closures.
Option 2:
+ (RACSignal *)createObject {
RACSignal *paramsSignal = [[[[self class] createObject1] flattenMap:^id(NSManagedObjectModel *object1) {
return [RACSignal combineLatest:#[[RACSignal return:object1], [[self class] createObject2:object1]]];
}] flattenMap:^RACStream *(RACTuple *tuple) {
return [RACSignal combineLatest:#[[RACSignal return:tuple.first], [RACSignal return:tuple.second], [[self class] createObject3:tuple.second]]];
}];
return [paramsSignal map:^id(RACTuple *tuple) {
return [[CombinedObject alloc] initWithO1: tuple.first O2: tuple.second O3: tuple.third];
}];
}
No nesting or closures but too much of tuples and objects are passing through each signal...
So I was wondering if there is more elegant solution I'm missing exist.
Thanks.
How about stack-like approach?
- (NSArray *) createPhases {
return #[#selector(createObject1:), #selector(createObject2:), #selector(createObject3:)];
}
...
+ (RACSignal *)createObject {
NSMutableArray *stack = [NSMutableArray new];
for (SEL phase: [self createPhases]) {
stack = [[[self class] performSelector:phase withObject:stack] flattenMap:^RACStream *(NSString *append) {
return [stack arrayByAddingArray:#[append]]; // or with some other manipulations
}];
}
return [self withObjects:stack map:^id(NSArray *stack) {
return [[CombinedObject alloc] initWithObjects:stack];
}];
}
- (...) createObject1:(NSArray *)chain {
// here chain will be empty, actually (#[])
return ... // create object 1
}
- (...) createObject2:(NSArray *)chain {
// here chain will be #[object1]
return [... ... withObject1:[chain lastObject]]; // create object 2
}
- (...) createObject3:(NSArray *)chain {
// here chain will be #[object1, object2]
return [... ... withObject2:[chain lastObject]]; // create object 3
}
This question already has answers here:
Restrict NSTextField to only allow numbers
(10 answers)
Closed 8 years ago.
In textfield I want to restrict numbers like (1234567890) and special characters but I want to allow alphanumeric characters. How I am suppose to do this?
Use the UITextField delegate method
textField:shouldChangeCharactersInRange:replacementString:
To check the string that is about to be replaced, if you allow it then return yes if not then return no.
Here is some more information.
Apple UITextField Delegate
try following code
+ (BOOL)isNumber:(NSString *)value {
if ( (value == nil) || ([#"" isEqualToString:value]) ) {
return NO;
}
int l = [value length];
BOOL b = NO;
for (int i = 0; i < l; i++) {
NSString *str =
[[value substringFromIndex:i]
substringToIndex:1];
const char *c =
[str cStringUsingEncoding:
NSASCIIStringEncoding];
if ( c == NULL ) {
b = NO;
break;
}
if ((c[0] >= 0x30) && (c[0] <= 0x39)) {
b = YES;
} else {
b = NO;
break;
}
}
if (b) {
return YES;
} else {
return NO;
}
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ( (string != nil) && (string != #"") ) {
if (![self isNumber:string]) {
return NO;
}
}
return YES;
}
You need to write a NSFormatter and assign it to your text field. Here an example implementation of a such NSFormatter which uses a NSRegularExpression to validate the NSTextField contents.
#interface XXNameElementFormatter : NSFormatter
#end
#implementation HcNameElementFormatter {
NSRegularExpression *_re;
}
- (id)init {
self = [super init];
if (self) {
[self initRegularExpression];
}
return self;
}
- (void)awakeFromNib
{
[self initRegularExpression];
}
- (void)initRegularExpression
{
NSError *reError;
_re = [NSRegularExpression regularExpressionWithPattern:#"^[a-z]*$" options:NSRegularExpressionCaseInsensitive error:&reError];
NSAssert(_re != nil, #"Error in regular expression, error: %#", reError);
}
- (NSString *)stringForObjectValue:(id)obj
{
return obj;
}
- (BOOL)getObjectValue:(out __autoreleasing id *)obj forString:(NSString *)string errorDescription:(out NSString *__autoreleasing *)error
{
*obj = string;
return YES;
}
- (BOOL)isPartialStringValid:(NSString *__autoreleasing *)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString *__autoreleasing *)error
{
NSParameterAssert(partialStringPtr != nil);
NSString *partialString = *partialStringPtr;
NSRange firstMatch = [_re rangeOfFirstMatchInString:*partialStringPtr options:0 range:NSMakeRange(0, partialString.length)];
return firstMatch.location != NSNotFound;
}
#end
I've made an implementation for an JSON-RPC (a little bit modified) Server/Client in objective-c with the GCDAsyncSocket library. but the app crashes on responding to an request. without debugging for zombies i'm getting this error:
JSONRPCTestServer(1301,0x7fff7f887960) malloc: *** error for object 0x10014db10: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
the screenshot in xcode shows the error is in the completeCurrentRead method of the GCDAsyncSocket library.
when debugging for zombies it logs this:
2013-02-04 14:36:16.430 JSONRPCTestServer[1367:603] *** -[__NSArrayI release]: message sent to deallocated instance 0x1005b6fd0
and instruments shows this:
as this happens when a response to the rpc-call is of type nsarray i'd guess its this array that is causing the error. the rpc-method is:
-(NSArray *)testArray:(GCDAsyncSocket *)sock {
return [NSArray arrayWithObjects:#"test1",#"test2", nil];
}
The JSON-RPC header is:
#import <Foundation/Foundation.h>
#import "JSONRPCMethod.h"
#import "JSONRPCResponse.h"
#import "JSONRPCError.h"
#import "JSONRPCArgument.h"
#import "JSONRPCRequest.h"
#import "GCDAsyncSocket.h"
#class GCDAsyncSocket;
#protocol JSONRPCResponseDelegate <NSObject>
#optional
-(void)rpcSocket:(GCDAsyncSocket*)sock returnedValue:(id)retVal forMethod:(NSString*)m id:(id)i;
-(void)rpcSocket:(GCDAsyncSocket*)sock returnedError:(JSONRPCError*)err forMethod:(NSString*)m id:(id)i;
-(void)rpcReturnedValue:(id)retVal forMethod:(NSString*)m id:(id)i;
-(void)rpcReturnedError:(JSONRPCError*)err forMethod:(NSString*)m id:(id)i;
#end
#interface JSONRPC : NSObject {
NSMutableArray *supportedMethods;
GCDAsyncSocket *mainSocket;
NSMutableArray *connectedSockets;
NSMutableArray *responseDelegates;
BOOL isServer;
}
+(JSONRPC*)sharedConnection;
-(BOOL)startServer:(NSUInteger)port;
-(BOOL)connectToServer:(NSString*)host port:(NSUInteger)port;
-(BOOL)addMethod:(JSONRPCMethod*)method;
-(void)removeMethod:(JSONRPCMethod*)method;
-(void)removeMethodsWithTarget:(id)target;
-(void)sendRequest:(JSONRPCRequest*)req toSocket:(GCDAsyncSocket*)sock;
-(void)sendRequest:(JSONRPCRequest*)req;
-(void)sendNotification:(JSONRPCRequest*)req toSocket:(GCDAsyncSocket*)sock;
-(void)sendNotification:(JSONRPCRequest*)req;
-(void)sendNotification:(JSONRPCRequest*)req toSocketsWithUserData:(id)userData;
#end
.m is:
#import "JSONRPC.h"
#import "GCDAsyncSocket.h"
#define kGeneralReadTimeout -1.0
#define kGeneralWriteTimeout -1.0
#implementation JSONRPC
- (id)init
{
self = [super init];
if (self) {
isServer = NO;
supportedMethods = [[NSMutableArray alloc] init];
mainSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
connectedSockets = [[NSMutableArray alloc] init];
responseDelegates = [[NSMutableArray alloc] init];
}
return self;
}
+ (JSONRPC *)sharedConnection {
static JSONRPC *sharedSingleton;
#synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[JSONRPC alloc] init];
return sharedSingleton;
}
}
-(BOOL)startServer:(NSUInteger)port {
// Now we tell the socket to accept incoming connections.
// We don't care what port it listens on, so we pass zero for the port number.
// This allows the operating system to automatically assign us an available port.
isServer = YES;
NSError *err = nil;
if ([mainSocket acceptOnPort:port error:&err]) {
} else {
DDLogError(#"Error while starting JSON-RPC Server: %#",err);
return NO;
}
DDLogInfo(#"Started JSON-RPC Server on port %hu",[mainSocket localPort]);
return YES;
}
-(BOOL)connectToServer:(NSString *)host port:(NSUInteger)port {
NSError *err = nil;
mainSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[mainSocket connectToHost:host onPort:port error:&err];
if(err != nil) {
DDLogError(#"Couldn't connect to host %#:%lu (Error: %#)",host,port,err);
return NO;
}
return YES;
}
-(BOOL)addMethod:(JSONRPCMethod *)method {
for (JSONRPCMethod *meth in supportedMethods) {
if([meth.name isEqualToString:method.name]) {
return NO;
}
}
[supportedMethods addObject:method];
return YES;
}
-(void)removeMethod:(JSONRPCMethod *)method {
[supportedMethods removeObject:method];
}
-(void)removeMethodsWithTarget:(id)target {
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (JSONRPCMethod *meth in supportedMethods) {
if(meth.target == target) {
[toRemove addObject:meth];
}
}
[supportedMethods removeObjectsInArray:toRemove];
}
-(void)sendRequest:(JSONRPCRequest *)req toSocket:(GCDAsyncSocket*)sock {
[responseDelegates addObject:req];
[req setIdentifier:[NSNumber numberWithUnsignedInteger:[responseDelegates count]-1]];
[self sendPackage:[req dictionary] toSocket:sock];
}
-(void)sendRequest:(JSONRPCRequest *)req {
[self sendRequest:req toSocket:mainSocket];
}
-(void)sendNotification:(JSONRPCRequest *)req toSocket:(GCDAsyncSocket*)sock{
[req setIdentifier:nil];
[self sendPackage:[req dictionary] toSocket:sock];
}
-(void)sendNotification:(JSONRPCRequest *)req {
[self sendNotification:req toSocket:mainSocket];
}
-(void)sendNotification:(JSONRPCRequest *)req toSocketsWithUserData:(id)userData {
NSMutableArray *matchingSockets = [[NSMutableArray alloc] init];
for (GCDAsyncSocket*sock in connectedSockets) {
if(sock.userData == userData) {
[matchingSockets addObject:sock];
}
}
if(matchingSockets.count == 0)
return;
[req setIdentifier:nil];
NSData *pkgData = [self writableDataFromDictionary:[req dictionary]];
for (GCDAsyncSocket*sock in matchingSockets) {
[sock writeData:pkgData withTimeout:kGeneralWriteTimeout tag:0];
}
}
#pragma mark Socket Delegate
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
[connectedSockets addObject:newSocket];
[newSocket readDataToData:[GCDAsyncSocket ZeroData] withTimeout:kGeneralReadTimeout tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
DDLogVerbose(#"socket:didConnectToHost:%# port:%hu", host, port);
[sock readDataToData:[GCDAsyncSocket ZeroData] withTimeout:kGeneralReadTimeout tag:0];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
DDLogVerbose(#"socketDidDisconnect:%#", err);
if(isServer)
[connectedSockets removeObject:sock];
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
// So, we've received something from the client
// As we have to cut out the last 0x00 for JSONSerialization it has to be longer than 1 byte
if(data.length > 1) {
// Shorten out that 0x00
data = [data subdataWithRange:NSMakeRange(0, data.length-1)];
// Try to serialize
NSError *err;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
DDLogVerbose(#"Dict: %#",dict);
if(err != nil) {
// The package isn't json
JSONRPCResponse *response = [JSONRPCResponse responseWithError:[JSONRPCError invalidRequest]];
[self sendPackage:[response dictionary] toSocket:sock];
} else {
JSONRPCResponse *response = [self handleDictionary:dict fromSocket:sock];
if(response != nil) {
[self sendPackage:[response dictionary] toSocket:sock];
}
}
}
[sock readDataToData:[GCDAsyncSocket ZeroData] withTimeout:kGeneralReadTimeout tag:0];
}
-(JSONRPCResponse*)handleDictionary:(NSDictionary*)dict fromSocket:(GCDAsyncSocket*)sock {
// Check if the "id" is of a correct value/type
id identifier = [dict valueForKey:#"id"];
if(!(identifier == nil || [identifier isKindOfClass:[NSNumber class]])) {
return [JSONRPCResponse responseWithError:[JSONRPCError invalidRequest]];
}
// Handle the package
NSString *methodName = [dict valueForKey:#"method"];
id errorValue = [dict valueForKey:#"error"];
id resultValue = [dict valueForKey:#"result"];
if([methodName isKindOfClass:[NSString class]]) {
// We have a string as method
DDLogInfo(#"Method: %#, object: %#",methodName,[dict valueForKey:#"params"]);
for (JSONRPCMethod *method in supportedMethods) {
if([method.name isEqualToString:methodName]) {
id result = nil;
if(isServer == YES) {
// It is a server and the method needs to know from where the call comes
result = [method invoke:[dict valueForKey:#"params"] fromSocket:sock];
} else {
// It is a client and we don't need to know where the call is from. it can only be the server.
result = [method invoke:[dict valueForKey:#"params"]];
}
if([result isKindOfClass:[JSONRPCError class]]) {
return [JSONRPCResponse responseWithError:result id:identifier];
} else if(result != nil) {
return [JSONRPCResponse responseWithResult:result id:identifier];
} else {
return nil;
}
}
}
} else if(resultValue != nil) {
// We have a response from our partner
//DDLogInfo(#"Result: %#",resultValue);
NSUInteger responseDelegateId = [identifier unsignedIntegerValue];
if(responseDelegateId < [responseDelegates count]) {
JSONRPCRequest *originalRequest = [responseDelegates objectAtIndex:responseDelegateId];
if(originalRequest.sender == nil) {
return nil;
}
#try {
SEL selector;
if(isServer) {
selector = #selector(rpcSocket:returnedValue:forMethod:id:);
} else {
selector = #selector(rpcReturnedValue:forMethod:id:);
}
NSMethodSignature *signature = [originalRequest.sender methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:originalRequest.sender];
[invocation setSelector:selector];
NSUInteger startArg = 2;
if(isServer) {
[invocation setArgument:&sock atIndex:startArg];
startArg++;
}
NSString *method = [originalRequest method];
id orgId = [originalRequest identifier];
[invocation setArgument:&resultValue atIndex:startArg];
[invocation setArgument:&method atIndex:startArg+1];
[invocation setArgument:&orgId atIndex:startArg+2];
[invocation invoke];
}
#catch (NSException *exception) {
DDLogWarn(#"Couldn't find a response: %#",exception);
}
}
} else if(errorValue != nil) {
// We have a string as method
DDLogInfo(#"Error: %#",errorValue);
} else {
return [JSONRPCResponse responseWithError:[JSONRPCError invalidRequest] id:identifier];
}
return nil;
}
-(void)sendPackage:(NSDictionary *)dict toSocket:(GCDAsyncSocket *)sock {
NSData *answerData = [self writableDataFromDictionary:dict];
[sock writeData:answerData withTimeout:kGeneralWriteTimeout tag:0];
}
-(NSData*)writableDataFromDictionary:(NSDictionary*)dict {
NSMutableData *answerData = [[NSMutableData alloc] init];
// Serialize the answer
NSError *err = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&err];
if(err != nil) {
// Log
DDLogError(#"JSON-RPC had an internal error while converting the answer to JSON. The answer-dictionary is: %#",dict);
// Form answer manually
jsonData = [NSData dataWithBytes:"{\"error\":{\"code\":-32700,\"message\":\"Parse error\"}}"
length:49];
}
// Format the answer
[answerData appendData:jsonData];
[answerData appendData:[GCDAsyncSocket ZeroData]];
return answerData;
}
i just don't know how to fix this. why do i keep getting an error with an nsarray but when i return a nsnumber it works? how can i fix this?
I'm taking a class and we're working on a Calculator program. My background is in C++. I am taking a RPN calculator entry of 3 enter sqrt and need to display it as sqrt(3) in my descriptionOfProgram method, which is new, including associated property below. Here's the class so far. Search for "xcode" to find my issues. Any ideas? I'm not very good at the basic objective c classes, but I'm trying to learn. Here's a summary:
it's complaining about my boolean. I'm not sure why. I did this in a different class and it worked fine.
it's looking for a { I don't see it
it doesn't like my use of the key. I'm unclear on how to get the key's contents I think is the problem.
It wants ] but I'm not seeing why
skipped
It expected } at #end
Hope you can help! Thanks!
//
// CalculatorBrain.m
// Calculator
//
// Created by Michele Cleary on 2/25/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic, strong) NSMutableArray *programStack;
#property (nonatomic, strong) NSDictionary *testVariable;
#property (nonatomic) BOOL numberHandledNextOperation;
- (double) convertRadianToDegree: (double) radian;
#end
#implementation CalculatorBrain
#synthesize programStack = _programStack;
#synthesize testVariable = _testVariable;
#synthesize numberHandledNextOperation = _numberHandledNextOperation;
- (NSMutableArray *)programStack
{
if (_programStack == nil) _programStack = [[NSMutableArray alloc] init];
return _programStack;
}
//- (void)setOperandStack:(NSMutableArray *)operandStack
//{
// _operandStack = operandStack;
//}
- (void)pushOperand:(double)operand
{
[self.programStack addObject:[NSNumber numberWithDouble:operand]];
}
- (double)performOperation:(NSString *)operation
{
[self.programStack addObject:operation];
return[CalculatorBrain runProgram:self.program];
}
- (id)program
{
return [self.programStack copy];
}
+ (NSString *)descriptionOfProgram:(id)program
{
self.numberHandledNextOperation = NO; //1. this is a problem with xcode: member reference type struct objc_class * is a pointer; maybe you meant to use ->
NSMutableSet * displayDescrip = [[NSMutableSet alloc] init];
for(id foundItemKey in program)
{
if ([foundItemKey isKindOfClass:[NSString class]])
//operator or variable
{
if ([foundItemKey isEqualToString:#"sin"]&&(!self.numberHandledNextOperation))
{ //2. xcode says To match this {.
NSObject *nextObj = [program objectForKey:(foundItemKey+1); //3. xcode doesn't like this: arithmetic on pointer to interface id which is not a constant size in non-fragile ABI
//[displayDescrip addObject:foundItemKey];
}
else if ([foundItemKey isEqualToString:#"cos"])
{
//[displayDescrip addObject:foundItemKey];
}
else if ([foundItemKey isEqualToString:#"sqrt"])
{
//[displayDescrip addObject:foundItemKey];
}
else if ([foundItemKey isEqualToString:#"Ï€"])
{
//[displayDescrip addObject:foundItemKey];
}
else if (![CalculatorBrain isOperationName:foundItemKey])
{
//variable
//[displayDescrip addObject:foundItemkey];
}
else if (foundItemKey isKindOfClass:[NSNumber class]) //4. xcode expected ]
{
//number
//if next object is operation
if(isOperation([program objectForKey:(foundItemKey+1)))
{
numberHandledNextOperation = YES;
if(isOperationSpecial([program objectForKey:(foundItemKey+1)))
{ //sin or cos or sqrt need parentheses
//[displayDescrip addObject:(foundItemKey+1)];
//[displayDescrip addObject:#"("];
//[displayDescrip addObject:foundItemKey];
//[displayDescrip addObject:#")"];
}
else
{ //regular operation + - / *
//[displayDescrip addObject:(foundItemKey+1)];
//[displayDescrip addObject:(foundItemKey)];
}
numberHandledNextOperation = YES;
} //if
} //else if
} //if
} //for
//not sure if I need this next thing
//NSSet * returnedVarNames = [varNames copy];
//return returnedVarNames;
return #"implement this in Assignment 2";
}
+ (double)runProgram:(id)program
{
NSMutableArray *stack;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
}
return [self popOperandOffStack:stack];
}
+ (double)runProgram:(id)program usingVariableValues:(NSDictionary *)variableValues
{
NSMutableArray *stack;
if ([program isKindOfClass:[NSArray class]]) {
stack = [program mutableCopy];
}
if(variableValues)
{
int numItemsDisplayed = [stack count];
for (int count = 0; count < numItemsDisplayed; count++)
{
id foundItem = [stack objectAtIndex:count];
if ([foundItem isKindOfClass:[NSString class]])
{
NSString * var = [variableValues objectForKey:foundItem];
if(var)
{
[stack replaceObjectAtIndex:count withObject:[NSNumber numberWithDouble:[var doubleValue]]];
}
}
}
}
return [self popOperandOffStack:stack];
}
+ (double)popOperandOffStack:(NSMutableArray *)stack
{
double result = 0;
id topOfStack = [stack lastObject];
if (topOfStack) [stack removeLastObject];
if([topOfStack isKindOfClass:[NSNumber class]]){ //number
result = [topOfStack doubleValue];
}
else if ([topOfStack isKindOfClass:[NSString class]]){ //string operation
NSString *operation = topOfStack;
if ([operation isEqualToString:#"+"]) {
result = [self popOperandOffStack:stack] + [self popOperandOffStack:stack];
}else if ([operation isEqualToString:#"*"]) {
result = [self popOperandOffStack:stack] * [self popOperandOffStack:stack];
}else if ([operation isEqualToString:#"/"]) {
double divisor = [self popOperandOffStack:stack];
if (divisor)
result = [self popOperandOffStack:stack] / divisor;
}else if ([operation isEqualToString:#"-"]) {
double subtrahend = [self popOperandOffStack:stack];
result = [self popOperandOffStack:stack] - subtrahend;
}else if ([operation isEqualToString:#"sin"]) {
result = result = (sin([self popOperandOffStack:stack])); //(sin([self convertRadianToDegree:[self popOperandOffStack:stack]]));
}else if ([operation isEqualToString:#"cos"]) {
result = (cos([self popOperandOffStack:stack]));
}else if ([operation isEqualToString:#"sqrt"]) {
result = (sqrt([self popOperandOffStack:stack]));
}else if ([operation isEqualToString:#"π"]) {
result = M_PI;
}else{
result = 0;
}
}
return result;
}
+ (NSSet *)variablesUsedInProgram:(id)program
{
NSMutableSet * varNames = [[NSMutableSet alloc] init];
for(id foundItem in program)
{
if ([foundItem isKindOfClass:[NSString class]])
{
if (![CalculatorBrain isOperationName:foundItem])
{
[varNames addObject:foundItem];
}
}
}
NSSet * returnedVarNames = [varNames copy];
return returnedVarNames;
}
+ (BOOL)isOperationName:(NSString *)foundItem
{
NSSet *myOperationSet = [NSSet setWithObjects:#"sqrt", #"sin", #"cos", #"π", #"+", #"-", #"*", #"/", nil];
return([myOperationSet containsObject:(foundItem)]);
}
- (NSString *)description
{
return [NSString stringWithFormat:#"stack = %#", self.programStack];
}
-(double) convertRadianToDegree: (double) radian;
{
return M_PI*2*radian/360;
}
#end //6. xcode expected }
+ (NSString *)descriptionOfProgram:(id)program
Do you actually want descriptionOfProgram a class + method ? If yes, it is more like a static method in C++. It doesn't belong to any particular instance of a class. There is no hidden parameter of constant pointer to the current instance is passed.