this is my code in ViewController.h in CoCoa to implement "CFsocket"
#interface ViewController : NSViewController
-(IBAction)start:(id)sender;
#property (strong, nonatomic) IBOutlet NSTextView *CommandDisplay;
this is ViewController.m
#implementation ViewController
#synthesize CommandDisplay=_CommandDisplay;
void AcceptCallBack(CFSocketRef socket,CFSocketCallBackType type,CFDataRef address,const void *data,void *info)
{
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
// For a kCFSocketConnectCallBack that failed in the background, it is a pointer to an SInt32 error code; for a kCFSocketAcceptCallBack, it is a pointer to a CFSocketNativeHandle; or for a kCFSocketDataCallBack, it is a CFData object containing the incoming data. In all other cases, it is NULL.
CFSocketNativeHandle sock = *(CFSocketNativeHandle *) data;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock, &readStream, &writeStream);
if (!readStream || !writeStream)
{
close(sock);
NSLog(#"CFStreamCreatePairWithSocket()Fail");
return;
}
CFStreamClientContext streamCtxt = {0, NULL, NULL, NULL, NULL};
CFReadStreamSetClient(readStream, kCFStreamEventHasBytesAvailable, ReadStreamClientCallBack, &streamCtxt);
CFWriteStreamSetClient(writeStream, kCFStreamEventCanAcceptBytes, WriteStreamClientCallBack, &streamCtxt);
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
CFReadStreamOpen(readStream);
CFWriteStreamOpen(writeStream);
}
// readstream operatoion , use when client transmitted data
void ReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void* clientCallBackInfo)
{
UInt8 buff[255];
CFReadStreamRef inputStream = stream;
CFReadStreamRead(stream, buff, 255);
_CommandDisplay.string=[self._CommandDisplay.string stringByAppendingString:[NSString stringWithFormat:#"SeverCreat failed\n"]];
NSLog(#"receiveļ¼ %s",buff);
NSLog(#"%#",clientCallBackInfo);
CFReadStreamClose(inputStream);
CFReadStreamUnscheduleFromRunLoop(inputStream,CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
inputStream = NULL;
}
when i use c function , it can't recognize _CommandDisplay which i have synthesize ,but i need to print read data to NSTextView,how can i solve this problem?
In Objective-C a synthesized property foo is backed by an implicit instance variable _foo.
If you want to access the instance variable directly use _foo without self.
If you want to access the property by its synthesized getter and setter use self.foo (without the underscore)
Write
self.CommandDisplay.string = [self.CommandDisplay.string stringByAppendingString:#"SeverCreat failed\n"];
or
_CommandDisplay.string = [_CommandDisplay.string stringByAppendingString:#"SeverCreat failed\n"];
NSString stringWithFormat is not needed, there are no format parameters, and you can also delete the #synthesize line, it's not needed either.
A small side-note:
If the C-function was outside the scope of the implementation block, you would have to pass the reference to the NSTextView instance thru the info parameter of the function, but in this case it should work
Related
We are creating an iOS binding library for an objective C static lib.
The following property is causing a compilation error. We have created the ApiDefinition files using Objective sharpie
Error BI1078: bgen: Do not know how to make a signature for System.Byte* in method `get_DataY' (BI1078)
// #required #property (readonly, nonatomic) const uint8_t * _Nonnull dataY;
[Abstract]
[Export("dataY")]
unsafe byte* DataY { get; }
What do we replace byte* with?
I have seen a lot of questions on SO about this theme but they don't ask my case.
Analyzer is giving me this warning
incorrect decrement of the reference count of an object that is not owned at that point by the caller
but in my case the method in question is not generating or is not intended to return any context.
My method is like this:
#property (nonatomic, assign) CGContextRef ctx;
- (void)generatePDFWithSize:(CGSize)size andURL:(NSURL*)url {
CGRect mediaBox = CGRectZero;
mediaBox.size = tamanho;
self.ctx = CGPDFContextCreateWithURL((__bridge CFURLRef)(URL), &mediaBox, NULL);
for (int i=0; i<numberOfPages; i++) {
CGPDFContextBeginPage(self.ctx, NULL);
//... bla bla bla... generate page
CGPDFContextEndPage(self.ctx);
}
CGContextRelease(self.ctx);
}
Analyzer is pointing to the last line.
How do I solve that?
You can keep a separate reference to your Context such as:
CGContextRef ctx = CGPDFContextCreateWithURL((__bridge CFURLRef)(URL), &mediaBox, NULL);
self.ctx = ctx;
Then you can release the context that you've created by calling:
CFRelease (ctx);
So you're not releasing the one that the compiler believes that self owns.
I've already searched "everything" about this in Google/Stackoverflow, but I'm still stuck. I have just started developing OSX Apps, so I'm a (almost) complete newbie in Objective-C and Xcode 5 (5.0.2).
All I need is a simple webview to load a webgame from a given URL. This webview must behave just like a very simple Safari browser. My app is already working relatively well. It loads the game OK, and after a lot of struggling I succeeded making it show javascript alerts and confirms.
THE POINT: I need to display a simple text message to the user, in case of no internet connection is detected, then I need to close the app. It seems a very trivial thing, but I can't find a way to do that!!
That's my appDelegate.M:
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize myWebView;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
// Check if there's internet connection:
#include <SystemConfiguration/SystemConfiguration.h>
static BOOL internetOk()
{
BOOL returnValue = NO;
struct sockaddr zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sa_len = sizeof(zeroAddress);
zeroAddress.sa_family = AF_INET;
SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr*)&zeroAddress);
if (reachabilityRef != NULL)
{
SCNetworkReachabilityFlags flags = 0;
if(SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
BOOL connectionRequired = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
returnValue = (isReachable && !connectionRequired) ? YES : NO;
}
CFRelease(reachabilityRef);
}
return returnValue;
}
// -
if(internetOk())
{
[self.window setContentView:self.myWebView];
[self.window toggleFullScreen:#""];
[self.myWebView setMainFrameURL:#"http://www.mywebgameurl.com"];
}
else
{
// SHOWS ERROR MESSAGE AND CLOSES APP! HOW CAN I DO IT????
}
}
#end
Any help is welcome, thanks!!
You're looking for the NSAlert class, check here for Apple's docs.
Sample usage:
NSAlert* alert = [NSAlert alertWithMessageText:#"Internet Error"
defaultButton:nil
alternateButton:nil
otherButton:nil
informativeTextWithFormat:#"No internet."];
[alert runModal];
My plugin code crashes when I call the NPN_GetValue. Basically I created a scriptable object which has a 'getDevice' method that can return a device array to JavaScript. Below is the code snippet.
static bool mainNPObjectInvoke(NPObject *obj, NPIdentifier identifier, const NPVariant *args, uint32_t argCount, NPVariant *result)
{
printf("create main object");
MainNPObject *mainObject = (MainNPObject *)obj;
if (identifier == methodIdentifiers[METHOD_ID_GET_DEVICES])
{
NPObject *windowObj = NULL;
browser->getvalue(mainObject->npp, NPNVWindowNPObject, &windowObj);
// it crashed here
....
}
}
I created the MainNPObject instance with below method.
NPObject *createMainNPObject(NPP npp)
{
MainNPObject *object = (MainNPObject *)browser->createobject(npp, &mainNPClass);
object->npp = npp;
theMainObject = object;
return (NPObject *)object;
}
The createMainNPObject is called in the plugin function I provided to browser.
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
PluginObject *obj = instance->pdata;
switch (variable) {
case NPPVpluginCoreAnimationLayer:
if (!obj->rootLayer)
setupLayerHierarchy(obj);
*(CALayer **)value = obj->rootLayer;
return NPERR_NO_ERROR;
case NPPVpluginScriptableNPObject:
if (!obj->mainObject)
{
obj->mainObject = createMainNPObject(instance);
}
....
}
And the allocate function is as below.
static NPObject *mainNPObjectAllocate(NPP npp, NPClass *class)
{
initializeIdentifiers();
MainNPObject *mainObject = malloc(sizeof(MainNPObject));
mainObject->deviceManager = [[DeviceManager alloc] init];
return (NPObject *)mainObject;
}
Definition of MainNPObject:
typedef struct
{
NPObject *npobject;
NPP npp;
DeviceManager *deviceManager;
} MainNPObject;
By debugging the code, I found that the system raised an EXC_BAD_ACCESS when calling the browser->getValue and it looks like the npp pointer is invalid.
0x00007fff83f82dab <+0019> je 0x7fff83f82db9 <_ZN6WebKit14NetscapePlugin7fromNPPEP4_NPP+33>
0x00007fff83f82dad <+0021> incl 0x8(%rax)
Can someone help me out?
Thanks!
Hmm; not seeing anything obvious. Try adding another parameter (an int?) to your structure and set it during allocate or immediately afterwords, then later on check to see if it's still the value you set before you call getvalue. See if your struct is somehow getting corrupt. That happened to me once when I was casting the NPObject funny in a non-obvious way.
I want to use an function to pass a lot of points to another function, but the Xcode has errors on the line with: CGContextAddLines......
the add points is filled with information like:
CGPoint addPoints[] = {
CGPointMake(10,10),
CGPointMake(10,10),
}
the use the
-(void) constructPoints:(CGContextRef) context withPoints:(CGPoint) addPoints {
// do some context set attributes, color
// and
CGContextAddLines(context, addPoints, sizeof(addPoints)/sizeof(addPoints[0]));
// and draw-it
}
Try it like this:
-(void) constructPoints:(CGContextRef) context withPoints:(CGPoint[]) addPoints numPoints:(int) size {
// do some context set attributes, color
// and
CGContextAddLines(context, addPoints, size);
// and draw-it
}
Then on your call:
[self constructPoints:yourContext withPoints:addPoints numPoints:sizeof(addPoints)/sizeof(addPoints[0])];